Home > front end >  delete operator usage when reassigning pointers - 2
delete operator usage when reassigning pointers - 2

Time:02-03

I asked this question earlier here: delete operator usage when reassigning pointers

Do you need to always delete a pointer when you reassign it to another pointer, Example:

 int value = 5;
 int* ptr{ new int{} }; // allocate memory
 ptr = &value; // old address lost, memory leak results

The answer I got: It's advisable to add delete before the reassignment to prevent a memory leak.

I am wondering though, that if value is pointing to the same object as ptr (and not to the int value 5 that is being declared), would this introduce a bug if I were to add delete ptr before reassignment? I understand that there would be a deeper problem in the code if there are two pointers pointing at the same object and should always maintain an 1-1 relationship. Is this something to consider? Thanks

CodePudding user response:

I think you are asking given two pointers p1 and p2 pointing to the same object obj, what would happen - besides memory leak - if you delete p1 and then assign something else to it.

In that case p2 would point to an invalid location in the memory (because it was deleted). An attempt to dereferencing it, like *p2, would be an undefined behavior (e.g. it might crash your program).

Using smart pointers will help to avoid such mistakes.

CodePudding user response:

If you're asking if

int value = 5;
int* ptr{ new int{} }; // allocate memory on heap
delete ptr; // This is fine
ptr = &value; // New ptr points to memory address of value
delete ptr; // This is not fine as value is allocated on the stack

The first delete is fine because you are deleting an object allocated on heap. The second delete is undefined behavior because the underlying address is allocated on the stack.

  •  Tags:  
  • Related