I am starting some threads using AfxBeginThread and they work by monitoring a flag (sent via lParam) and once they find the flag is set, they return. However, once they do return, they aren't deleted and I get a memory leak.
Shouldn't this method work fine and not cause any memory leaks because m_bAutoDelete is by default set to true? I've read that it's best to just allow the thread to return by itself, and it'll just automatically delete itself.
Here's the code I'm testing:
UINT ThreadProc(LPARAM lParam) {
CThreadTestDlg* pDlg = (CThreadTestDlg*) lParam;
char str[128];
int counter = 0;
pDlg->m_running = true;
while (pDlg->m_running) {
sprintf_s(str, "Counter: %d", counter);
pDlg->m_text.SetWindowText(str);
counter++;
Sleep(1000);
}
return 0;
}
void CThreadTestDlg::OnBnClickedStart()
{
if (!m_running) AfxBeginThread((AFX_THREADPROC)ThreadProc, this);
}
void CThreadTestDlg::OnBnClickedStop()
{
OutputDebugString("\n-------- Start --------\n");
_CrtMemState state;
_CrtMemCheckpoint(&state);
_CrtMemDumpStatistics(&state);
OutputDebugString("--------- End ---------\n\n");
m_running = false;
}
And this is my debug output, where you can see how the memory leak occurs:
-------- Start --------
0 bytes in 0 Free Blocks.
0 bytes in 0 Normal Blocks.
9085 bytes in 49 CRT Blocks.
0 bytes in 0 Ignore Blocks.
132 bytes in 2 Client Blocks.
Largest number used: 9749 bytes.
Total allocations: 15192 bytes.
--------- End ---------
The thread 'Win32 Thread' (0xdd8) has exited with code 0 (0x0).
-------- Start --------
0 bytes in 0 Free Blocks.
0 bytes in 0 Normal Blocks.
9085 bytes in 49 CRT Blocks.
0 bytes in 0 Ignore Blocks.
132 bytes in 2 Client Blocks.
Largest number used: 9749 bytes.
Total allocations: 16324 bytes.
--------- End ---------
The thread 'Win32 Thread' (0x1114) has exited with code 0 (0x0).
-------- Start --------
0 bytes in 0 Free Blocks.
0 bytes in 0 Normal Blocks.
9085 bytes in 49 CRT Blocks.
0 bytes in 0 Ignore Blocks.
132 bytes in 2 Client Blocks.
Largest number used: 9749 bytes.
Total allocations: 17456 bytes.
--------- End ---------
The thread 'Win32 Thread' (0x1090) has exited with code 0 (0x0).