Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't this code crash

int *p;
while(true)
{
 p = new int;
}

Due to running out of memory space, shouldn't this code crash. I have tried printing out the value of p, that is the address of memory located for p, and it seems to increase yet there is no crashing.

Why is this so?

like image 688
Shamim Hafiz - MSFT Avatar asked Oct 25 '10 17:10

Shamim Hafiz - MSFT


3 Answers

This solution is like trying to crash a car at a telephone pole down the street while driving 1MPH. It will happen eventually but if you want fast results you need to up the speed a bit.

int *p;
while (true) { 
  p = new int[1024*1024*1024];
}

My answer though is predicated on your code base using the standard STL allocator which throws on a failed memory allocation. There are other available allocators which simply return NULL on a failed allocation. That type of allocator will never crash in this code as the failed allocation is not considered fatal. You'd have to check the return of the allocation for NULL in order to detect the error.

One other caveat, if you're running on a 64 bit system this could take considerably longer to crash due to the increased size of the address space. Instead of the telephone poll being down the street, it's across the country.

like image 103
JaredPar Avatar answered Oct 18 '22 13:10

JaredPar


Looks like you won't close this question until you see a crash :)

On Unix like operating system you can restrict the amount of virtual memory available to a process using the ulimit command. By setting the VM to 1MB I was able to see the desired results in about 5 seconds:

$ ulimit -v $((1024*1024)) # set max VM available to process to 1 MB

$ ulimit -v                # check it.
1048576

$ time ./a.out             # time your executable.
terminate called after throwing an instance of 'St9bad_alloc'
  what():  std::bad_alloc
Aborted

real    0m5.502s
user    0m4.240s
sys  0m1.108s
like image 9
codaddict Avatar answered Oct 18 '22 14:10

codaddict


Sseveral allocations of small chunks of memory is slower than one big allocation. For instance, it will take more time to allocate 4 bytes 1 million times, than 1 million bytes 4 times.

Try to allocate bigger chunks of memory at once:

int *p;
while(true)
{
 p = new int[1024*1024];
}
like image 7
KeatsPeeks Avatar answered Oct 18 '22 15:10

KeatsPeeks