Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing unallocated memory C++

I am having this piece of code:

try
{
    int* myTestArray = new int[2];

    myTestArray[4] = 54;

    cout << "Should throw ex "  << myTestArray[4] + 1 << endl;
}
catch (exception& exception)
{ 
    cout << "Exception content: " << exception.what() << endl;
}

What is really curios for me, is that why the exception is not thrown here, since it was accessed an index which was not allocated... and why 55 is print ? Is that C++ automatically increased the size of the array ?

like image 901
Clock Avatar asked Jan 10 '15 20:01

Clock


2 Answers

Accessing unallocated memory is not guaranteed to throw exceptions.

It's actually not guaranteed to do anything, since that's undefined behavior. Anything could happen. Beware of nasal demons.

It prints 55 because you just stored 54, fetched it back and then printed 54+1. It's not at all guaranteed to print 55, although that's often what will happen in practice. This time it worked.

like image 153
tux3 Avatar answered Sep 24 '22 00:09

tux3


There is an unstated, and incorrect, assumptions here. That assumption is that C++ actually gives a damn about what you do with memory. C++, like its C ancestor, has a completely unchecked model of memory. What you have here is classically called a buffer overflow, and is a source of innumerable bugs including some horrible security flaws.

Here's what your code really says:

  • myTestArray is the name of a location in memory big enough to hold the address of an int.

  • Two ints worth of memory have been allocated on the heap for it. [And that addreress is put into the location myTestArray. Doesn't matter, but that probably makes it clearer.] (Along with probably 16 bytes of overhead, but we don't care about that now.)

  • you then are sticking the value 54 into the memory location 4 ints from the address contained in myTestArray.

  • looking at that location, adding 1 and printing the result.

You are demonstrating that C(++) indeed just doesn't care.

Now, under most conditions the underlying memory management and run time system won't let you get away with it; you will violate it's assumptions and get a segmentation error or something similar. But in this case, you are not hitting a boundary yet, most likely because you're piddling on the data structure that malloc is using under the covers to manage the heap. You're getting away with it because nothing is happening with the heap for the rest of the program. But for a real good time, write a little loop that does this code, freeing myTestArray and reallocating it. I'd lay long odds it won't run for more than 10 iterations before the program blows up, and might not make two.

like image 36
Charlie Martin Avatar answered Sep 23 '22 00:09

Charlie Martin