1

I have an MFC dialog, which is called Dlg1

myobject* Dlg1 = new myobject();

This dialog has a parent dialog called A; I have a function in A, which is called on closing:

A::Destroy()
{
     if(Dlg1 )
           delete  Dlg1; // this is triggering `DebugBreak(); here i get A.exe has triggered a breakpoint, 
     // the rest of the code 
}

If I close Dlg1 dialog, manually by clicking on the close button, then close the main dialog A, then everything is fine no problem. However, if Dlg1 is running and I close A, then I get DebugBreak(). This issue occurs only in debug mode, in the release mode no problem.

Samer
  • 1,923
  • 3
  • 34
  • 54
  • _'Does anyone know what triggers this?'_ Deleting an already deleted pointer for instance ... – πάντα ῥεῖ Jul 21 '14 at 21:29
  • 1
    The debug heap detected heap corruption. Nice feature. Finding the cause is of course never simple. – Hans Passant Jul 21 '14 at 21:29
  • 2
    There is no need to check for NULL when issuing a call to `delete`. So that check for `if(Dlg1 )` doesn't help you at all, unless you're calling Destroy() on the same object multiple times in succession. – PaulMcKenzie Jul 21 '14 at 21:31
  • It might help putting a `Dlg1 = nullptr;` after the `delete` statement (thus `if(Dlg1 )` makes sense). – πάντα ῥεῖ Jul 21 '14 at 21:31
  • 2
    @Samer _'I do this '_ So, why don't you show it in your sample? Did you think it's irrelevant? – πάντα ῥεῖ Jul 21 '14 at 21:44
  • 2
    @Samer - Is this code correct `myobject* Dlg1 = new myobject();`? If so, then that `Dlg1` is a local variable, different than the `Dlg1` you have in your `Destroy` method, or it is (heaven forbid) a global variable. – PaulMcKenzie Jul 21 '14 at 21:52

1 Answers1

2

If we are to assume that the code you posted in your question is the actual code you're using, the issue may be this:

myobject* Dlg1 = new myobject();

Note that Dlg1 is a local variable, not a member variable. Then you have this:

A::Destroy()
{
  if (Dlg1 )
     delete  Dlg1; 
}

The Dlg1 in the code above is the member variable Dlg1 of class or struct A. It more than likely was never initialized, due to your code creating a dynamic object locally by mistake. Issuing a delete on an uninitialized pointer will wreak havoc.

If this is the issue, then to fix it, one suggestion is to have somewhere:

A::SomeFuntion()
{
    //...
    Dlg1 = new myobject();  // set the member variable Dlg1, not a local variable.
    //...,
}

where SomeFunction would be another member function of A.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
  • Paul, Dlg1 is a member of A. – Samer Jul 21 '14 at 22:24
  • I am sure 'Dlg1' is not deleted explicitly, However, Before A is closed or Destroyed, I called `Dlg1->Onclose()` which calls `Dlg1->OnDestroy()`, so if the last call already deleted Dlg1 then yes, this is double delete then. – Samer Jul 21 '14 at 22:33