Do I need to delete a pointer if I haven't assigned it a new value?
Asked Answered
M

1

10

Just a quick question:

Do I need to delete a pointer if I haven't actually assigned a new value to it?

What I've done if created a pointer and then handed it a reference to something like so:

Planet *planetPointer;

planetPointer = &earth;

Do I need to delete this pointer or can I just set it to null?

Mcburney answered 4/12, 2012 at 18:15 Comment(4)
Only delete what you new.Krafftebing
To be a little more pedantic than @chris: The rule is that for every new you should have a delete at some point, and for every new[] you should have a delete[] at some point.Dasi
Duplicate - #12513926Retral
possible duplicate of C++ calling delete on variable allocated on the stackLake
W
19

You don't need to delete it, and, moreover, you shouldn't delete it. If earth is an automatic object, it will be freed automatically. So by manually deleting a pointer to it, you go into undefined behavior.

Only delete what you allocate with new.

Wootten answered 4/12, 2012 at 18:15 Comment(2)
To put it another way: If you didn't new the object, you don't have ownership of it (unless relevant documentation says otherwise), and if you don't have ownership of it you shouldn't deallocate it.Navarrete
Even worse, in a way, is when earth is a reference to a dynamically allocated object. Assuming that other author was a good citizen, that earth object will eventually be freed by the thing that allocated it. Delete it here and the program will fail on that later deletion. The reason this is nastier is because the error message makes it appears that the error is at the second delete. The author of the earth-allocating code will inevitable receive a nasty phone call or email saying "Your code is broken! It's dropping core."Zephan

© 2022 - 2024 — McMap. All rights reserved.