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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Joseph Little
  • 921
  • 3
  • 13
  • 22
  • 12
    Only `delete` what you `new`. – chris Dec 04 '12 at 18:15
  • 4
    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. – Nik Bougalis Dec 04 '12 at 18:16
  • Duplicate - http://stackoverflow.com/questions/12513426/what-happens-when-delete-pointer-to-stack-object?lq=1 – user93353 Dec 04 '12 at 18:19
  • possible duplicate of [C++ calling delete on variable allocated on the stack](http://stackoverflow.com/questions/441831/c-calling-delete-on-variable-allocated-on-the-stack) – John Dibling Dec 04 '12 at 18:58

1 Answers1

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • 1
    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. – cdhowie Dec 04 '12 at 18:16
  • 1
    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." – David Hammen Dec 04 '12 at 18:34