Link to home
Start Free TrialLog in
Avatar of RockyNando2

asked on

Microsoft, VC++ MFC 2005, UI Thread delete causing heap corruption

Hi all,
I am attempting to create an MFC app which uses multiple UI threads. I have my main app class 'CThreadApp' and a class which derives from CWinThread  'UIThread.'
Inside the InitInstance function of CThreadApp i have
BOOL CThreadApp::InitInstance()

      //Create 'IsWorking' dialog in separate thread (thread is a UIThread)
      some code
      //Tell the 'IsWorking' dialog to close
::SendMessage(thread.m_pMainWnd->m_hWnd, WM_COMMAND, IDOK, 0);

return FALSE;

And the InitInstance and Run functions of UIThread are:

BOOL UIThread::InitInstance()
      return TRUE;

int UIThread::Run()
      CSQLScriptRunnerDlg dlg;
      m_pMainWnd = &dlg;

      INT_PTR nResponse = dlg.DoModal();

      //m_bAutoDelete = FALSE; <- Ill come to this in a sec

      return 0;

My problem is that after I send the IDOK message to the UIThread, the dialog closes but i get an error stating: This may be due to a corruption of the heap, and indicates a bug in ThreadApp.exe or any of the DLLs it has loaded.

After some debugging I found that it is a call to pThread->Delete() causing this, and that if I include the line 'm_bAutoDelete = False;' (commented out in the code above), the error does not occur, but instead I get a different error, an Access Violation as the application attempts to destroy a dialog with a NON NULL m_pMainWnd.

So my question is what exactly is causing the error, and is there a way to make sure that this thread terminates without causing an error?

As always thanks for any help in advance.
Avatar of bandyt1712
Flag of Germany image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RockyNando2


Yes that was it, in the destructor of CWinThread, it attempts to delete m_pMainWnd if it is not null, so setting it to null fixed the issue, cheers.