我在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的时候会发生故障,因为它无法进行分页。在创建交换文件后,我的问题就消失了。
感谢您的帮助
printf(“%d”,sizeof(svm_node))并告诉我们结果 – 2011-02-16 03:51:23
sizeof(svm_node):16 – josephmisiti 2011-02-16 13:41:14