Search code examples
c++dynamic-memory-allocationnew-operator

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?


Solution

  • 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.