Search code examples
c++dynamic-memory-allocationdelete-operator

Do I need to delete pointer which pointing pointer in heap?


    Class example
{
};

int main()
{
  Example* pointer1 = new example();
  Example* pointer2;
  pointer2 = pointer1;
  delete pointer1;
}

Should I delete pointer2? I think it's in the stack and I don't need to delete.


Solution

  • Short answer: No.

    pointer1 and pointer2 are both pointers which exist on the stack. new Example allocates on the heap a new object of type Example, and its memory address is stored in pointer1. When you do delete pointer1, you are freeing the memory allocated on the heap. Since both pointer1 and pointer2 are both referencing the same memory location at the point of the delete call, it does not need to also be deleted, in fact, this would be Undefined Behaviour, and could cause heap corruption or simply your program to crash.

    At the end of this, both pointer1 and pointer2 are still pointing to the same block of memory, neither are actually nullptr.