繁体   English   中英

Malloc在64位Ubuntu机器上失败

[英]Malloc Failing on 64-Bit Ubuntu box

我在具有18 GB RAM的64位Ubuntu机器上运行以下代码,并且如您所见,当我尝试分配2 ^ 31字节时,对Malloc的调用失败。 我不确定为什么会这样,或者如何解决(我已经尝试过编译器标志以及calloc())。 我想知道是否有人可以向我解释为什么我不能在64位设备上分配更多空间以及如何解决此问题。

#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

更新:

我发现了我遇到的问题:我目前在64位Ubuntu linux发行版上的EC2上运行我的代码,EC2上的默认linux框的交换空间为0。 当它请求的内存量大于物理RAM时,这导致我的进程出现故障,因为它无法分页。 创建交换文件后,我的问题消失了。

谢谢你的帮助

pow()是一种计算2的幂的可怕方法。请改用1 << i

然后,选择一个足以容纳您要求的大小的数据类型。 现在,它溢出了int的大小,因此尝试分配负数的字节。 由于明显的原因,这不起作用。

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

接下来,您要分配的空间远远超过问题提到的2 31字节,实际上是在分配2 i * sizeof (svm_node)或大约2 i + 4 i=30的失败分配大约是16GB,这可能比您的可用RAM还要大。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM