I have a code
#include <iostream>
using namespace std;
int main()
{
while(true)
{
try
{
new int;
}
catch(std::exception e)
{
}
}
return 0;
}
So, when I run this code under Linux, my computer freezes when memory is end (as expected), but when I'm on Windows, my app crashes after allocating 3 gb of memory (usually I have 1 gb used, and 16 in total). Why it crashes? How to prevent this?
When I replace new int
with malloc(1)
, after allocating these 3 gb, memory isn't going to allocate more
My guess is that it crashes under Windows is simply that you compile it as x86 and not as x64 executable. x86 executables have a limitation of 3GB of RAM because it runs out of adresses. Under Linux you compile 64bit by default (on a 64bit machine using g++), so it does not crash here but freezes the system, as the system is using the swap space after its out of RAM which is damn slow. If the SWAP also fills up, your system is simply going down. Compile the Windows version as 64bit and see what happens then.
My assumption for this text is you have a 64bit machine (otherwise you wouldnt be able to use those 16GB of RAM).
Now, when using malloc
instead of new
, your program wont crash, as malloc has error states. It will simply give you a NULL
pointer back as it is not able to allocate more memory. new
does not.