所以我有这个程序分配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 中为二维 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)