开发者

Dynamic memory allocation "delete"

If I allocated a memory location for an int object dynamically as follows:

int *x = new int;

After done with it, and want to free the memory on the heap, I开发者_如何学Go will do the following:

delete x;

Now, if I did not do the following:

x = NULL;

Will x be pointing to another address? UPDATE: another instead of many

Say I didn't do x = NULL and made another delete x;, what will happen?


  1. Anything you do with x (apart from = NULL - which is, imo, bad practice) after you delete it is undefined.
  2. double-delete = disaster.

Note: some runtime systems will protect you from certain very simple cases of double delete. Depending on the details, you might be okay if you happen to be running on one of those systems and if no one ever deploys your code on another system that handles things differently and if you are deleting something that doesn't have a destructor and if you don't do anything significant between the two deletes and if no one ever changes your code to do something significant between the two deletes and if your thread scheduler (over which you likely have no control!) doesn't happen to swap threads between the two deletes and if, and if, and if. So back to Murphy: since it can go wrong, it will, and it will go wrong at the worst possible moment.

https://isocpp.org/wiki/faq/freestore-mgmt


After the delete, the pointer will typically still contain the address of the (now free) memory. The second delete gives undefined behavior, so don't do that.


It will invoke undefined behavior. If you don't do x=NULL then x will be pointing to an invalid memory location which if you try to use will cause undefined behavior.


type:

int main(){
  int* i = new int;
  std::cout << i << std::endl;
  delete i;
  std::cout << i << std::endl;
  delete i;
}

result:

0x8e19008

0x8e19008

** glibc detected ** ./a.out: double free or corruption (fasttop): 0x08e19008 *

as you see, the address stays the same, but the second delete ends in a runtime error. behaviour may in detail depend on environment, but as a general rule it will not work.


calling delete on already deleted memory will cause undefined behaviour. Generally, your program will crash.

After deleting x, where it will be pointing is "compiler dependent". Most of the compilers will just let it point to where it was, before delete was called. But that memory address is no more valid, and hence should not be called.

For this same reason, "delete this" must be used very judiciously and carefully, if at all needed. :-)


The secondth delete is undefined.

As a side note, there are tools to detect a double deletion. One of the best one around is Valgrind.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜