CreateThread memory leaks



  • I wrote the code.

    #include <cstdio>
    #include <Windows.h>
    

    DWORD __stdcall MyThread(void*) {
    printf("Hello, Thread!\n");
    return 0;
    }

    int main() {
    HANDLE h = ::CreateThread(nullptr, 0, MyThread, nullptr, 0, nullptr);
    ::WaitForSingleObject(h, INFINITE);
    ::CloseHandle(h);
    }

    And I'm told there's gonna be a memory leak, and I need to use it. _beginthread[ex] or std::thread♪ Why is that?



  • The functions of the rank (CRT) are stored in the local memory of the flow (Thread Local Storage, TLS). It looks like,

    PerThreadData* ptd = TlsGetValue();
    if (!ptd) {
      ptd = new PerThreadData;
      TlsSetValue(ptd);
    }
    

    In the first appearance of CRT, for example printf a memory block for global CRT - errno, elbows, etc. - Everything that's unique to the flow.

    If the flow is created CreateThreadas in the code on the question, when the TLS flow is purified, and the entire dedicated memory leaks.

    In Visual C++ there is a function _beginthreadwhich detracts its flow function so that PerThreadData was removed after completion of the flow:

    struct WrapperParams {
      void (*user_fn)(void*);
      void* user_arg;
    };
    

    DWORD __stdcall thread_fn_wrapper(WrapperParams* params) {
    params->user_fn(params->user_arg);
    delete params;

    PerThreadData* ptd = TlsGetValue();
    delete ptd;
    }

    uintptr_t _beginthread(void(start_address)(void),
    unsigned stack_size,
    void* arglist) {
    WrapperParams* params = new WrapperParams{start_address, arglist};
    HANDLE h = ::CreateThread(0, stack_size, thread_fn_wrapper, params, 0, 0);
    ::CloseHandle(h);
    }

    Class std::thread He also knows about the CRT memory block, and he also cleans his memory.


    Note: FLS is used for software (fiber) instead of TLS.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2