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
- How could an element with index number 15 exist, if I’m allocating only 10?
- 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?
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.
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.