Pointer to deallocated location Is it a Undefined Behavior?

女生的网名这么多〃 提交于 2019-12-13 10:14:36

问题


Pointer to deallocated location Is it a Undefined Behavior?

http://ideone.com/Qp3uY

int *p = new int;

*p = 10;

delete p;

*p = 10;

cout << *p << endl;

回答1:


There mere existence of a pointer to a deallocated location is not undefined behavior in itself. Attempting to dereference that pointer does produce undefined behavior though.




回答2:


Dereferencing a deleted pointer is an undefined operation. Don't do it.




回答3:


This is undefined behavior:

If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value, the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. The effect of using an invalid pointer value (including passing it to a deallocation function) is undefined. - C++ '03 3.7.3.2




回答4:


When you allocate memory to make a new pointer, as you do in the first line

int *p = new int;

You're asking the operating system to produce some memory for you to use, for as long as you like. You can then put something in that spot, as you then do

*p = 10;

This memory is available for you to use as long as you want, and then you can tell the operating system you're done with it, by calling delete, as you do on the next line.

delete p;

The operating system now has the memory available to it, but it may or may not do something with that memory. If you allocate a bunch of other memory, it is possible that the new memory range includes this memory. The operating system may give away this memory to something else, or it may not - it's not going to tell you, that's why it is said to be undefined behavior to still use that place in memory.

*p = 10;

You then reuse this place of memory to set it to 10 again. Nothing else has happened in the meantime and this is a rather trivial program, so the operating system hasn't done anything else with that block of memory yet, so setting it in this case does not have any greater effect.

cout << *p << endl;

Again, the operating system owns the memory right now, but it isn't likely doing anything with it at this point; it's like staying in a hotel room after your stay is officially over. You may or may not be able to stay there, as you don't know whether the room is being used by another person afterward or if it is remaining empty. You could be thrown out, or you could be safe.



来源:https://stackoverflow.com/questions/10662587/pointer-to-deallocated-location-is-it-a-undefined-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!