0

Say I have the following C++ code:

void f() {
MyClass *p = new Class();
delete p;
}

Here, I avoided a memory leak because I deleted whatever that was in the heap. My question is, do I need to make p a null pointer, to avoid it from being a dangling pointer, like so: p = nullptr;

I think the answer is I don't need to make it point to null because when we go out of scope of the function, everything that's on the stack is deleted automatically, meaning that the pointer p is automatically deleted.

jas305
  • 89
  • 1
  • 8
  • That's correct. Dangling pointers are only an issue when you might accidentally dereference it later. – cigien Oct 26 '20 at 19:26
  • 2
    `p` is not a dangling pointer, since it is not being used anymore after the `delete`. But if you were still using it after the `delete`, then yes, you would have to set it to null so that later code can know whether it is still pointing at a valid `MyClass` object or not. – Remy Lebeau Oct 26 '20 at 19:26
  • You do not have to do it, but sometimes you want to. – SergeyA Oct 26 '20 at 19:26
  • No, you do not **need** to set a dangling pointer to `nullptr`, as long as you do not dereference it after the delete. You may want to set it to `nullptr` if you could use the pointer later, and check to make sure it isn't `nullptr` (used as a sentinel value). But in the example provided, it is all contained within the routine. – Eljay Oct 26 '20 at 19:28
  • In my experience, you never need to assign pointers to null after delete occurs. This is assuming that code is all handling correctly. – Ilan Keshet Oct 26 '20 at 19:28
  • 2
    which is a big assumption ;) – NathanOliver Oct 26 '20 at 19:28
  • 1
    Note: If you haven't already, look into smart pointers like [`std::unique_ptr`](https://en.cppreference.com/w/cpp/memory/unique_ptr). They're very helpful in guaranteeing a resource is freed after everyone (with degrees of "everyone" varying by the type of smart pointer used) is done using it. – user4581301 Oct 26 '20 at 19:38

0 Answers0