Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
i have following question related to memory managment,source from where i am reading this article says that, When a variable goes out of scope, that memory is no longer guaranteed to store the variable’s value example code is given
int main() {
int *p;
if (true) {
int x = 5;
p = &x;
}
cout << *p << endl; // ???
}
it says also that Here, p has become a dangling pointer (points to memory whose contents are undefined) but this code shows me result 5.so that is wrong in writing such code?please explain me
The key phrase "no longer guaranteed". The behaviour is undefined. It might work, or it might not, depending on what your compiler decides to do.
You cannot rely on this behaviour. So you should never write code like that.
When an object is deleted, the range of memory that was used to store that object is deallocated. This only means that other processes are now free to use this memory range. The values stored there will remain unchanged until written over by another process.
It's fairly analogous to when you 'delete' something in windows. What you are actually doing is telling the system that you are allowing it to use this space for something else. If you try to recover the file immediately then there is a fairly good chance that nothing else has written over that part of your hard drive yet. If instead you waited a couple of days then there's a significant chance that another file will have been written over it.
Dangling pointers therefore cannot guarantee to return the value you initially stored there.
I think it is because .. address hold by p still having the value of address x in local scope, but compiler is now free to allocate that space. so the behavior is totally undefined.
after this block:
if (true) {
int x = 5;
p = &x;
}
variable x
was unrolled from stack, so memory it was occupying is free for reuse. And it can be reused at any time.
Your code leaves you with the address of a variable no longer existing. The C++ standard makes no claim what happens to that memory. Dereferencing the pointer will yield Undefined Behavior.
Unfortunately, one way of UB to manifest itself is by the code appearing to work.
after }
the x
variable memory get free and you use that memory out of }
.
精彩评论