Home > front end >  std::vector does not release memory in a thread
std::vector does not release memory in a thread

Time:03-23

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?

CodePudding user response:

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.

CodePudding user response:

As you can see in the documentation for _endthreadex, _endthreadex causes C destructors pending in the thread not to be called.

So just remove the call to _endthreadex and you should be fine.

The reasons for this behaviour are explained in this answer.

  • Related