当有足够的内存时,为什么malloc()失败? [英] Why does malloc() fail when there is enough memory?
问题描述
我正在使用具有128GB内存的服务器进行一些计算.我需要 malloc()
大小为56120 * 56120的2D浮点数组.示例代码如下:
I'm using a server with 128GB memory to do some computation. I need to malloc()
a 2D float array of size 56120 * 56120. An example code is as follows:
int main(int argc, char const *argv[])
{
float *ls;
int num = 56120,i,j;
ls = (float *)malloc((num * num)*sizeof(float));
if(ls == NULL){
cout << "malloc failed !!!" << endl;
while(1);
}
cout << "malloc succeeded ~~~" << endl;
return 0;
}
代码可以成功编译,但是当我运行它时,它显示为"malloc failed !!!"
.根据我的计算,整个阵列仅需要大约11GB的内存.在开始代码之前,我检查了服务器,发现有110GB的可用内存.为什么会发生错误?
The code compiles successfully but when I run it, it says "malloc failed !!!"
. As I calculated, it only takes about 11GB of memory to hold the whole array. Before I started the code, I checked the server and there was 110GB of free memory available. Why does the error happen?
我还发现,如果将 num
减少到40000,则malloc将成功.
I also found that if I reduce num
to, say 40000, then the malloc will succeed.
这是否意味着 malloc()
可以分配的最大内存有限制?
Does this mean that there is a limit on the maximum memory that can be allocated by malloc()
?
此外,如果我更改分配方式,则直接声明具有这种大小的2D浮点数组,如下所示:
Moreover, if I change the way of allocation, directly declaring a 2D float array of such size, as follows:
int main(int argc, char const *argv[])
{
int num = 56120,i,j;
float ls[3149454400];
if(ls == NULL){
cout << "malloc failed !!!" << endl;
while(1);
}
cout << "malloc succeeded ~~~" << endl;
for(i = num - 10 ; i < num; i ++){
for( j = num - 10; j < num ; j++){
ls[i*num + j] = 1;
}
}
for(i = num - 11 ; i < num; i ++){
for( j = num - 11; j < num ; j++){
cout << ls[i*num + j] << endl;
}
}
return 0;
}
然后我编译并运行它.我收到细分错误"
.
then I compile and run it. I get a "Segmentation fault"
.
我该如何解决?
推荐答案
问题是,您的计算
(num * num) * sizeof(float)
作为32位有符号整数计算完成,并且num = 56120的结果为
is done as 32-bit signed integer calculation and the result for num=56120 is
-4582051584
然后解释为size_t的值非常大
Which is then interpreted for size_t with a very huge value
18446744069127500032
您没有太多的内存;)这就是 malloc()
失败的原因.
You do not have so much memory ;) This is the reason why malloc()
fails.
将 num
转换为 size_t
,然后它将按预期工作.
Cast num
to size_t
in the calculation of malloc, then it should work as expected.
这篇关于当有足够的内存时,为什么malloc()失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!