开发者

Deleting a pointer to an automatic variable [duplicate]

This question already has an answer here: W开发者_如何学运维hat is the behavior of "delete" with stack objects? [duplicate] (1 answer) Closed 8 years ago.

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?


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜