【发布时间】:2014-12-22 15:28:52
【问题描述】:
我正在编写一个需要使用一些非常大的数组的 C 程序。我通过调用为我的数组分配内存:
unsigned long *visited = declareArrayofLongs(my_pow(2, d));
declareArrayofLongs() 函数是:
unsigned long int* declareArrayofLongs(unsigned long int length)
{
unsigned long int *myarray = (unsigned long int*) malloc(length*sizeof(unsigned long int));
if (myarray==NULL)
printf("Error allocating memory for unsigned longs!\n");
unsigned long int i;
for(i=0; i<length; i++)
myarray[i] = 0;
return myarray;
}
而my_pow() 是
unsigned long int my_pow(int base, int exp)
{
unsigned long int pow=1;
int i=0;
for(i=0; i<exp; i++){
pow = (unsigned long int)base*pow;
}
return pow;
}
当程序运行并达到 d=29 左右时,我收到“为 unsigned long 分配内存时出错!”。我的系统上有 16GB 的 RAM。我不应该能够处理这么多的分配吗?
一次只声明一个visited 数组。在重新分配之前,我有一个free(visited) 电话。
【问题讨论】:
-
这并不取决于您使用的硬盘数量。这取决于操作系统为您分配了多少堆内存。
-
如果您查看映射文件或链接描述文件,它可以帮助您了解您的程序有多少堆内存可用。这真的不取决于你的物理记忆。
-
虽然和你的问题无关,但不要投
malloc()的返回值。见stackoverflow.com/q/605845/3488231 -
1)
sizeof(unsigned long): 4, 8, 是什么? 2)SIZE_MAX的值是多少? -
@twalberg:在执行进程时,整个可执行映像是否必须在内存中?我非常(尽管不完全)确定它不会。