Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does deleting a pointer delete the memory it's pointing too?

If I have a pointer like so:

int *test = new int;

And I create another pointer that points to test like so:

int *test2 = test;

Then I delete test2:

delete test2;

Does that mean that it will delete the memory of test as well, or would I have to call delete test also?

like image 303
user1583115 Avatar asked Aug 07 '12 22:08

user1583115


2 Answers

You never delete the memory for test, nor do you delete the memory for test2. The only thing that ever gets deleted is the object *test, which is identical to the object *test2 (since the pointers are the same), and so you must only delete it once.

This is a very common and very unfortunate misnomer that propagates and spoils the minds of people new to C++: One often speaks colloquially of "freeing a pointer" or "deleting a pointer", when you really mean "freeing memory to which I have a pointer", or "deleting an object to which I have a pointer". It's true that the relevant constructions (i.e. std::free and delete) take as their argument a pointer to the entity in question, but that doesn't mean that the pointer itself is operated on -- it merely communicates the location of the object of interest.

like image 165
Kerrek SB Avatar answered Sep 21 '22 07:09

Kerrek SB


Yes, the memory will be deleted freed as both pointers point to the same memory.

Furthermore, test will now be a dangling pointer(as will test2) and dereferencing it will result in undefined behaviour.

like image 34
Luchian Grigore Avatar answered Sep 20 '22 07:09

Luchian Grigore