title: Windows malloc replacement (e.g., tcmalloc) and dynamic crt linking
body: <p>A C++ program that uses several DLLs and QT should be equipped with a malloc replacement (like <a href="http://code.google.com/p/google-perftools/" rel="nofollow noreferrer">tcmalloc</a>) for performance problems that can be verified to be caused by Windows malloc. With linux, there is no problem, but with windows, there are several approaches, and I find none of them appealing:</p>
  
  <p><strong>1. Put new malloc in lib and make sure to link it first <a href="https://stackoverflow.com/questions/120627/is-there-a-way-to-redefine-malloc-at-link-time-on-windows">(Other SO-question)</a></strong></p>
  
  <p>This has the disadvantage, that for example <a href="http://benjamin.smedbergs.us/blog/2008-01-10/patching-the-windows-crt/" rel="nofollow noreferrer">strdup will still use the old malloc and a free may crash the program</a>.</p>
  
  <p><strong>2. Remove malloc from the static libcrt library with lib.exe (Chrome)</strong></p>
  
  <p>This is tested/used(?) for <a href="http://groups.google.com/group/google-perftools/browse_thread/thread/41cd3710af85e57b" rel="nofollow noreferrer">chrome/chromium</a>, but has the disadvantage that it just works with static linking the crt. Static linking has the problem if one system library is linked dynamically against msvcrt there may be <a href="https://stackoverflow.com/questions/787216/should-i-link-to-the-visual-studio-c-runtime-statically-or-dynamically">mismatches in the heap allocation/deallocation</a>. If I understand it correctly, tcmalloc could be linked dynamically such that there is a common heap for all self-compiled dlls (which is good).</p>
  
  <p><strong>3. Patch crt-source code (firefox)</strong></p>
  
  <p><a href="http://benjamin.smedbergs.us/blog/2008-01-10/patching-the-windows-crt/" rel="nofollow noreferrer">Firefox's jemalloc</a> apparently patches the windows CRT source code and builds a new crt. This has again the static/dynamic linking problem above.</p>
  
  <p>One could think of using this to generate a dynamic MSVCRT, but I think this is not  possible, because the license forbids providing a patched MSVCRT with the same name.</p>
  
  <p><strong>4. Dynamically patching loaded CRT at run time</strong></p>
  
  <p>Some commercial memory allocators can do such magic. tcmalloc can do, too, but this seems rather ugly. It had some issues, but they have been fixed. Currently, with tcmalloc it does not work under 64 bit windows.</p>
  
  <p>Are there better approaches? Any comments?</p>