1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • have you tried running it? may be you can add the result of your run and we can discuss it then? – Nim Dec 03 '10 at 08:59
  • Why not compile it and see? I get a segfault... – Kricket Dec 03 '10 at 09:01
  • `*** error for object 0x7fff5fbff5ec: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug` while running it... compiled with g++ 4.1 in MacOS X. By my definition of "running" it is not running fine. – David Rodríguez - dribeas Dec 03 '10 at 09:06

3 Answers3

5

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.

Community
  • 1
  • 1
Chubsdad
  • 24,777
  • 4
  • 73
  • 129
1

delete p; is UB and so any further behavior can't be predicted or relied upon. You program might crash immediately or spend all your money or just exit from main() and pretend nothing happened.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
0

Line 3 is definitely undefined behaviour, since you're trying to deleting memory at an address that is not on the heap.