Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading