Astronought
Astronought

Reputation: 445

Deleting pointers that point to the same variable

The code below is a condensed version of a code extract from a book, the idea was to create a copy of the ptr variable, then have the ptr variable point to a different address and finally delete the temporary pointer.

If my understanding is correct, does calling delete on the temporary pointer actually delete the original num variable? And since both the temporary pointer and num are dangling pointers is it correct to set them both to NULL?

int *num = new int(5);
int num1 = 10;

int *ptr = num;
int *temp = ptr;

ptr = &num1;

delete temp;
temp = NULL;
num = NULL;

Upvotes: 0

Views: 115

Answers (2)

Jts
Jts

Reputation: 3527

If my understanding is correct, does calling delete on the temporary pointer actually delete the original num variable? And since both the temporary pointer and num are dangling pointers is it correct to set them both to NULL?

Yes, because ptr & num point to exactly the same allocated memory address and the delete operator just needs that address, it doesn't care which variable holds that address.

And since both the temporary pointer and num are dangling pointers is it correct to set them both to NULL?

It's not needed to set them to NULL (use nullptr if you are using C++11). But if you end up using those dangling pointers by mistake later, with a debugger it's a lot easier to catch the problem if the pointers are set to nullptr.

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49921

Yes: the one thing you allocated gets deleted. I'm not sure what you mean by it being correct to assign NULL to variables, but in as much as their values before doing so no longer point to allocated memory, it certainly isn't a bad idea.

Upvotes: 2

Related Questions