If I create a thread with _beginthreadex
, and in the thread I used std::vector<WCHAR>
that consumes 200MB of memory - when the thread ends, the memory is not released. Even after CloseHandle
, the memory is not released.
Here is a working example:
#include <windows.h>
#include <process.h>
#include <vector>
using namespace std;
unsigned __stdcall Thread_RestartComputer(void* pComputerName)
{
std::vector<WCHAR> asdf(100000000);
_endthreadex(0);
return 0;
}
int main()
{
UINT threadID = 0;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_RestartComputer, 0, CREATE_SUSPENDED, &threadID);
ResumeThread(hThread);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
}
I thought that std::vector<WCHAR>
released the memory when it went out of scope?
C++ doesn't know that calling
_endthreadex
makes the thread go away. So it doesn't call the destructors of local variables likeasdf
before it calls_endthreadex
.Solution: Don't do that.
return 0;
ends the thread and calls the destructor.