我写了一些代码到calloc内存,直到没有更多的可用。MS Windows和Linux之间的Calloc差异?
#include <stdlib.h>
#include <iostream>
using namespace std;
int main()
{
int *p;
int count = 0;
while(1)
{
int inc=1024*1024*sizeof(char);
p=(int*) calloc(1,inc);
count++;
if(!p)
{
cout << "managed to allocate " << (count * 1024 * 1024)/1000000000.0 << " gb\n";
return 1;
}
}
}
在Visual Studio执行在Windows上面的代码中,我得到如下:
managed to allocate 1.9881 gb
Press any key to continue . . .
然而,当我把它给我的Linux系统,并编译和以下运行:
g++ mem.cpp
./a.out
这个进程在os后被os所杀死。
看起来即使分配的内存不存在,calloc也不会返回null?
如果是这样的话,那么我如何修改我现有的代码以在Linux上实现与Windows相同的效果?
为什么你用coC++调用calloc()而不是使用标准库的[动态内存管理](http://en.cppreference.com/w/cpp/memory)特性? –
在C++中,我会推荐使用'new'而不是'calloc',然后尝试处理['bad_alloc'](http://en.cppreference.com/w/cpp/memory/new/bad_alloc) – CoryKramer
@CoryKramer否,不要“新”。请参阅我一直在链接的内容。 –