【发布时间】:2014-03-14 18:38:14
【问题描述】:
所以基本上我想使用 malloc() 函数在我的计算机上找到可用的 Gb 数(只是整个 Gbs,忽略分数 Gb)。这是我使用的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argv, char **argc) {
unsigned long size = 0;
void *part[1000];
int i = 0;
part[size] = (void *)malloc(1024*1024*1024);
if(part[size] == 0)
printf("The computer has less than 1 Gb of free memory\n");
else {
while((part[size] != NULL) && (size<1000)) {
size++;
part[size] = (void *)malloc(1024 *1024 *1024);
}
while(i <= size) {
free(part[size]);
}
printf("The computer has %luGb of free memory\n", size);
}
return 0;
}
结果是分段错误(核心转储),我真的不知道为什么会发生这种情况,如果有人能指出我错在哪里,我将不胜感激。 谢谢:)
【问题讨论】:
-
请注意,由于memory overcommitment,这种方法不会告诉您有多少可用内存(至少在 Linux 上没有)。
-
再多的修复代码也不能让它做你想做的事。真正的问题是什么?
标签: c memory-management segmentation-fault malloc