Native memory leak in mixed DLLs upon thread creation RRS feed

  • Question

  • Problem definition:

    Creation of each new thread produces memory leak.

    Investigation results:

    Upon creation of new thread each DLL loaded in the process gets a call to DllMain (in case of native DLLs) or CorDLLMain in case of managed DLLs (DLL_THREAD_ATTACH).

    On thread destruction the same process is done with parameter DLL_THREAD_DETACH.

    In case of pure managed DLLs or pure native DLLs this mechanism works fine (i.e. no memory leaks).

    In case of mixed (Managed C++ or C++/CLI) DLLs each call to CorDLLMain produces a leak of 12 bytes of native memory (heap 150000). Leak remains after thread is destroyed.

    As a result, if threads are created and destroyed frequently, process accumulates huge memory leaks.

    Leak stack looks like this:

            mscoreei! operator new+00000043 
            mscoreei! RtlPcToFileHeader+0000D34F 
            mscoreei! GetThunkUseState+0000002C 
            mscoreei! CorDllMain+0000007F 
            mscoree! ShellShim __ CorDllMain+000000E1 
            mscoree! CorDllMain_Exported+00000037 
            ntdll! LdrpInitializeThread+00000163 
            ntdll! LdrpInitialize+000000AF 
            ntdll! LdrInitializeThunk+0000000E 


    As a workaround we disable DLL notificaitons on thread creation by calling DisableThreadLibraryCalls API function for each mixed DLL.

    (Frequent thread creation / destruction cannot be avoided at this stage).


    VS2010, .NET 4.0, process loads all kinds of DLLs: pure .NET, pure native and mixed DLLs.

    Problem happens both with Managed C++ and C++/CLI DLLs.

    Problem easily reproduces with primitive tester application.

    Most of threads are managed threads created in C# code.

    Note: This problem does not happen with VS2005 / .NET 2.0.


    Is it known problem?

    What is root cause?

    Is there solution available?

    Thursday, April 11, 2013 12:27 PM

All replies