#include "A.h"
int main (int argc, char*argv[]){
A * p_a1 = new A();
A * p_a2 = p_a1;
delete p_a1;
p_a1 = 0;
delete p_a2 <br>
Could this code where A is some class lead to memory management issues?
My Thoughts:
The first line will create a pointer to A. I am not sure if this will allocate memory for A, too, or will it just assign an address? The second pointer p_a2 points to the exact location.
delete p_a1 will delete the allocated memory, which probably didn't have anything p_a1=0, making it null. delete p_a2. We are then deleting the null pointer, which probably won't affect
Could this lead to any memory leakage or issues?
CodePudding user response:
Deleting the same object twice is definitely a memory management issue. delete p_a1;
does delete the object pointed to by p_a1
, then delete p_a2
tries to delete the very same object.
Remember: You are not deleting pointers, but you delete the object they are pointing to.
Raw new
is always a code smell and a potential source of bugs. Your code should look like this instead:
#include "A.h"
int main (int argc, char*argv[]){
A a;
}
Frankly, given your question imho one can either only scratch the surface or write a long article to explain important basics. I opted for the first and refer you to a book for more details: The Definitive C Book Guide and List
CodePudding user response:
Your problem is that p_a1
and p_a2
are independant pointers which at a time happen to point to the very same object.
After
delete p_a1;
p_a1 = 0;
all is fine from a p_a1
point of view: the object it pointed to has been deleted, and the pointer itself as received a nullptr
value, so it is now safe to do delete p_a1
again.
But p_a2
has not been changed and now points to an object that has reached its end of life. So it has become a dangling pointer and dereferencing it or deleting it will invoke UB.
If you want p_a2
to be equivalent to p_a1
you should make it a reference:
A* &p_a2 = p_a1;
Now after p_a1 = 0
, p_a2
is a reference to a null pointer and it can safely be deleted.