2011-02-16 107 views
0

我在64位Ubuntu盒子上运行以下代码,并使用18 GB的RAM,正如你所看到的,当我尝试分配2^31时,对Malloc的调用失败字节。我不知道为什么会发生这种情况,或者如何解决它(我已经尝试过编译器标志和calloc())。我想知道是否有人能向我解释为什么我无法在64位盒子上分配更多空间,以及我如何解决这个问题。Malloc在64位Ubuntu盒子上失败

#include <stdio.h> 
#include <stdlib.h> 
//#include "svm_model_matlab.h" 
//include "svm.h" 
#include <math.h> 


struct svm_node 
{ 
     int index; 
     double value; 
}; 


//#define Malloc(type,n) (type *)calloc(n,sizeof(type)) 
#define Malloc(type,n) (type *)malloc((n)*sizeof(type)) 

int main() 
{ 

     int i; 
     for(i =25; i< 35; ++i) 
     { 
       printf("2^%d %d \n", i,(long int) pow(2,i)); 
       svm_node* x_space = Malloc(struct svm_node,pow(2,i)); 
       printf("the address is %x\n", x_space); 
       free(x_space); 
     } 


     return 0; 
} 

输出:

2^25 33554432 
the address is 8513e010 
2^26 67108864 
the address is 6513e010 
2^27 134217728 
the address is 2513e010 
2^28 268435456 
the address is a513e010 
2^29 536870912 
the address is a513e010 
2^30 1073741824 
the address is 0 
2^31 -2147483648 
the address is 0 
2^32 0 
the address is 0 
2^33 0 
the address is 0 
2^34 0 
the address is 0 

更新:

我发现这个问题我是有:我目前正在运行我的代码在EC2上一个64位的Ubuntu Linux发行版,默认的Linux EC2上的盒子有0个交换空间。这导致我的进程在请求的任何内存量超过物理RAM的时候会发生故障,因为它无法进行分页。在创建交换文件后,我的问题就消失了。

感谢您的帮助

+0

printf(“%d”,sizeof(svm_node))并告诉我们结果 – 2011-02-16 03:51:23

+0

sizeof(svm_node):16 – josephmisiti 2011-02-16 13:41:14

回答

4

pow()是计算2.使用1 << i,而不是权力一个可怕的方式。

然后,选择一个足够大的数据类型来容纳您请求的大小。现在它溢出的大小为int,因此试图分配负数字节。这显然不起作用。

我怀疑malloc(1ULL << 31)会在您的系统上成功,没有任何问题。

接下来,你分配远远超过你的问题中提到的2 字节,你实际上是试图分配2 * sizeof (svm_node),或约2 我+ 4。失败的分配与i=30,大约为16GB,这可能会比你的免费RAM多。

最后,您在打印指针时会获得32位值。改为尝试printf("%p", x_space);。如果仍然为您提供32位值,请尝试使用64位编译器。