Search code examples
c++runtime-errorundefined-behaviordelete-operatormemory-corruption

Deleting a pointer to an automatic variable


Please look at this code

int i = 10;                                     //line 1 
int *p = &i;                                    //line 2  
delete p;                                       //line 3 
cout << "*p = " << *p << ", i = " << i << endl; //line 4  
i = 20;                                         //line 5  
cout << "*p = " << *p << ", i = " << i << endl; //line 6  
*p = 30;                                        //line 7
cout << "*p = " << *p << ", i = " << i << endl; //line 8  

What is the result of this code? Especially of line 3, 5 and 7? Do they invoke undefined behavior? What would be the output?

EDIT : I tried running it using g++, and it's compiling and running fine! I'm using MinGW on Windows 7.

What does Standard say in this context?


Solution

  • You can delete only a pointer if you have ever allocated it dynamically using new. In this case you have not allocated the pointer using new but simply defined and initialized it to point to a local variable of type int.

    Invoking delete on a pointer not allocated dynamically using new is something called Undefined Behavior. In short, it means that anything on the earth can happen when such a code is executed and you can't complaint a bit to anyone on this planet.