microsoft / STL

MSVC's implementation of the C++ Standard Library.
Other
10.07k stars 1.49k forks source link

Mark `at_thread_exit` list as CRT block #4418

Open AlexGuteniev opened 7 months ago

AlexGuteniev commented 7 months ago

https://github.com/microsoft/STL/blob/c53ac59abae552e50654943f7f80f23376a8039a/stl/src/xnotify.cpp#L41-L45

StephanTLavavej commented 7 months ago

I strongly suspect, but haven't confirmed, that these allocations show up as leaks in the CRT debug heap leak tracking machinery.

Arup-Chauhan commented 7 hours ago

I wrote a small test program to investigate the memory leak:

#include <crtdbg.h>
#include <cstdlib>
#include <thread>

void at_thread_exit_func() {
    int* simulated_leak = (int*) malloc(sizeof(int) * 100);
}

void thread_func() {
    at_thread_exit_func();
}

int main() {
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    std::thread t1(thread_func);
    std::thread t2(thread_func);
    t1.join();
    t2.join();
    _CrtDumpMemoryLeaks();
    return 0;
}

The test showed a memory leak:

Detected memory leaks!
{178} normal block at 0x0000020BEE9884C0, 400 bytes long.
{177} normal block at 0x0000020BEE989AD0, 400 bytes long.
Object dump complete.

This confirms the leak in the at_thread_exit mechanism.


I wanted to know if I have a proper test code.

If it is ok, perhaps we can fix the leak by wrapping the allocations inside _CrtMemCheckpoint at the start and _CrtMemDumpAllObjectsSince at the end of the critical section in the at_thread_exit_func. This will track and free the allocated memory properly when the thread exits.

@StephanTLavavej @CaseyCarter @AlexGuteniev feedback please.