mercredi 6 juillet 2022

Heap corruption on deleting a pointer twice stored in different classes

Two classes A and B share pointer to a third class C and when either A or B are deleted they call delete C as well.

Issue is not observed when only either of A or B is deleted. An exception is getting thrown in this scenario. I have specifically tried to set the class C pointer to NULL and have put in a NULL check to avoid this specific scenario but this null check is somehow not working.

I have read around that shared pointer should be used in this case but I am not sure how to implement it properly. It looks like whole code base needs to be changed to include shared_ptr everywhere as all class C objects would be updated to shared_ptr. Is there a way I can use shared_ptr just to store this pointer without changing all the code?

Edit: I have specifically deleted assignment operator and copy constructor of C to avoid situation both have different pointers due to copying. Can anything else can be done to prevent copying as pointed in answer by john

class A{
  C* c;
}
~A(){
  if(C != NULL){
  delete C;
  C = NULL;
 }
}

class B{
 C* c;
}

~B(){
  if(C != NULL){
  delete C;
  C = NULL;
 }
}

Aucun commentaire:

Enregistrer un commentaire