Search code examples
c++multithreadingmemoryvectorbeginthreadex

std::vector does not release memory in a thread


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?


Solution

  • C++ doesn't know that calling _endthreadex makes the thread go away. So it doesn't call the destructors of local variables like asdf before it calls _endthreadex.

    Solution: Don't do that. return 0; ends the thread and calls the destructor.