相关疑难解决方法(0)

为什么malloc没有"耗尽"我电脑上的内存?

所以我有这个程序分配256 MB的内存,并在用户按下ENTER后释放内存并终止.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char *p, s[2];

    p = malloc(256 * 1024 * 1024);
    if ( p == NULL) 
        exit(1);

    printf("Allocated"); 
    fgets(s, 2, stdin);
    free(p);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我多次运行这个程序并对每个程序进行后台处理,直到没有足够的内存可以分配.但是,这从未发生过.我运行了一个linux top命令,甚至在多次运行这个程序之后,空闲内存永远不会下降到256 MB.

但是,另一方面,如果我使用calloc而不是malloc那时有一个巨大的差异:

p = calloc(256 * 1024 * 1024, 1);

现在,如果我运行该程序并对其进行后台处理,并重复,每次运行它时,可用内存将减少256 MB.为什么是这样?为什么不会malloc导致可用的可用内存发生变化,但是calloc呢?

c linux malloc memory-management

12
推荐指数
3
解决办法
2424
查看次数

在C中为二维数组重新分配内存

我的目标是在 C 中为二维 int 数组动态重新分配内存。我知道已经有几个关于该主题的问题,但不幸的是我的代码无法正常运行,我不知道出了什么问题。

首先我分配内存:

int n = 10;
int m = 4;
int** twoDimArray;
twoDimArray = (int**)malloc(n * sizeof(int*));
for(int i = 0; i < n; i++) {
   twoDimArray[i] = (int*)malloc(m * sizeof(int));
}
Run Code Online (Sandbox Code Playgroud)

并用整数初始化数组:

for(int i = 0; i < n; i++) {
   for(j = 0; j < 4; j++) {
      twoDimArray[i][j] = i * j;
   }
}
Run Code Online (Sandbox Code Playgroud)

然后我用来realloc()动态重新分配内存:

int plus = 10;
int newArraySize = n + plus;
twoDimArray = (int**)realloc(twoDimArray, newArraySize * sizeof(int)); …
Run Code Online (Sandbox Code Playgroud)

c realloc

1
推荐指数
1
解决办法
380
查看次数

标签 统计

c ×2

linux ×1

malloc ×1

memory-management ×1

realloc ×1