Question

In the following code:

int main(int argc,char * argv[]){
  int * ptr;
  ptr = 0; // tried also with NULL , nothing changes
  ptr = new int[10]; // allocating 10 integers
  ptr[2] = 5;
  ptr[15] = 15;  // this should cause error (seg fault) - but it doesn't

  cout << ptr[2] << endl;
  cout << ptr[15] << endl;  // no error here

  delete [] ptr;

  cout << ptr[2] << endl;   // prints the value 5
  cout << ptr[15] << endl;  // prints the value 15
}

The result of the execution is:

5        
15        
5        
15        
  1. How could an element with index number 15 exist, if I'm allocating only 10?
  2. Why do the pointers still have values after the whole array is deallocated?

I tried delete with single allocation like this:

int * ptr;
ptr = 0;
ptr = new int;
*ptr = 5;
cout << *ptr << endl;
delete ptr ;
cout << *ptr << endl;

The result is normal:

5        
0        

Tested with gcc 4.7.2 and gcc 4.1.2 on fedora 17 and another platform (SLC5 - red hat based linux ), in order to make sure it does not depend on the compiler. What am I doing wrong here?

Was it helpful?

Solution

  1. The element beyond intended size of array exists, because the memory there happened to exist. Doing anything with it is illegal and leads to the dark unknown.

  2. The deallocation means that the memory isn't allocated for you anymore. It doesn't mean that someone went there and cleaned it up. But accessing what's left of you there is illegal and leads to the dark unknown.

OTHER TIPS

You are accessing memory that does not belong to the array. It works because of pure luck. If the program does not crash, it means that you are overwriting parts of memory that belong to your own application, and thus you ruin something somewhere and it can no longer be guaranteed that your program functions correctly.

Mostly you will get a segmentation fault, because you access memory of other applications. This time, you are just 'lucky'. Or as I would call it 'unlucky', because you can't immediately tell from the execution that your program has memory errors.

Dereferencing a deleted pointer is undefined behaviour as defined by the C++ standard. And it is just that- undefined behaviour. You could crash, you could get 0, you could get what was there previously, or 42. There is no "normal" behaviour at that point by definition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top