<p>I'm working on a <strong>multithreaded</strong> C++ application that is corrupting the heap.  The usual tools to locate this corruption seem to be inapplicable.  Old builds (18 months old) of the source code exhibit the same behaviour as the most recent release, so this has been around for a long time and just wasn't noticed; on the downside, source deltas can't be used to identify when the bug was introduced - there are <em>a lot</em> of code changes in the repository.</p>

<p>The prompt for crashing behaviuor is to generate throughput in this system - socket transfer of data which is munged into an internal representation.  I have a set of test data that will periodically cause the app to exception (various places, various causes - including heap alloc failing, thus: heap corruption).</p>

<p>The behaviour seems related to CPU power or memory bandwidth; the more of each the machine has, the easier it is to crash.  Disabling a hyper-threading core or a dual-core core reduces the rate of (but does not eliminate) corruption.  This suggests a timing related issue.</p>

<p>Now here's the rub:<br>
When it's run under a lightweight debug environment (say <code>Visual Studio 98 / AKA MSVC6</code>) the heap corruption is reasonably easy to reproduce - ten or fifteen minutes pass before something fails horrendously and exceptions, like an <code>alloc;</code> when running under a sophisticated debug environment (Rational Purify, <code>VS2008/MSVC9</code> or even Microsoft Application Verifier) the system becomes memory-speed bound and doesn't crash (Memory-bound: CPU is not getting above <code>50%</code>, disk light is not on, the program's going as fast it can, box consuming <code>1.3G</code> of 2G of RAM).  So, <strong>I've got a choice between being able to reproduce the problem (but not identify the cause) or being able to idenify the cause or a problem I can't reproduce.</strong></p>

<p>My current best guesses as to where to next is:</p>

<ol>
<li>Get an insanely grunty box (to replace the current dev box: 2Gb RAM in an <code>E6550 Core2 Duo</code>); this will make it possible to repro the crash causing mis-behaviour when running under a powerful debug environment; or</li>
<li>Rewrite operators <code>new</code> and <code>delete</code> to use <code>VirtualAlloc</code> and <code>VirtualProtect</code> to mark memory as read-only as soon as it's done with.  Run under <code>MSVC6</code> and have the OS catch the bad-guy who's writing to freed memory.  Yes, this is a sign of desperation: who the hell rewrites <code>new</code> and <code>delete</code>?!  I wonder if this is going to make it as slow as under Purify et al.</li>
</ol>

<p>And, no: Shipping with Purify instrumentation built in is not an option.</p>

<p>A colleague just walked past and asked "Stack Overflow?  Are we getting stack overflows now?!?"</p>

<p>And now, the question: <strong>How do I locate the heap corruptor?</strong></p>

<hr>

<p>Update: balancing <code>new[]</code> and <code>delete[]</code> seems to have gotten a long way towards solving the problem.  Instead of 15mins, the app now goes about two hours before crashing.  Not there yet.  Any further suggestions? The heap corruption persists.</p>

<p>Update: a release build under Visual Studio 2008 seems dramatically better; current suspicion rests on the <code>STL</code> implementation that ships with <code>VS98</code>.</p>

<hr>

<blockquote>
  <ol start="3">
  <li>Reproduce the problem. <code>Dr Watson</code> will produce a dump that might be helpful in further analysis. </li>
  </ol>
</blockquote>

<p>I'll take a note of that, but I'm concerned that Dr Watson will only be tripped up after the fact, not when the heap is getting stomped on.</p>

<blockquote>
  <p>Another try might be using <code>WinDebug</code> as a debugging tool which is quite powerful being at the same time also lightweight.</p>
</blockquote>

<p>Got that going at the moment, again: not much help until something goes wrong.  I want to catch the vandal in the act.</p>

<blockquote>
  <p>Maybe these tools will allow you at least to narrow the problem to certain component.</p>
</blockquote>

<p>I don't hold much hope, but desperate times call for...</p>

<blockquote>
  <p>And are you sure that all the components of the project have correct runtime library settings (<code>C/C++ tab</code>, Code Generation category in VS 6.0 project settings)?</p>
</blockquote>

<p>No I'm not, and I'll spend a couple of hours tomorrow going through the workspace (58 projects in it) and checking they're all compiling and linking with the appropriate flags.
<hR>
Update: This took 30 seconds.  Select all projects in the <code>Settings</code> dialog, unselect until you find the project(s) that don't have the right settings (they all had the right settings).</p>

[{'answer_id': 1072, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 1, 'selected': False, 'text': "<p>You tried old builds, but is there a reason you can't keep going further back in the repository history and seeing exactly when the bug was introduced?</p>\n\n<p>Otherwise, I would suggest adding simple logging of some kind to help track down the problem, though I am at a loss of what specifically you might want to log.</p>\n\n<p>If you can find out what exactly CAN cause this problem, via google and documentation of the exceptions you are getting, maybe that will give further insight on what to look for in the code.</p>\n"}, {'answer_id': 1073, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': True, 'text': '<p>My first choice would be a dedicated heap tool such as <a href="https://support.microsoft.com/en-us/kb/286470" rel="noreferrer">pageheap.exe</a>.</p>\n\n<p>Rewriting new and delete might be useful, but that doesn\'t catch the allocs committed by lower-level code. If this is what you want, better to Detour the <code>low-level alloc API</code>s using Microsoft Detours.</p>\n\n<p>Also sanity checks such as: verify your run-time libraries match (release vs. debug, multi-threaded vs. single-threaded, dll vs. static lib), look for bad deletes (eg, delete where delete [] should have been used), make sure you\'re not mixing and matching your allocs.</p>\n\n<p>Also try selectively turning off threads and see when/if the problem goes away.</p>\n\n<p>What does the call stack etc look like at the time of the first exception?</p>\n'}, {'answer_id': 1086, 'author': 'Piotr Tyburski', 'author_id': 2090742, 'author_profile': 'https://Stackoverflow.com/users/2090742', 'pm_score': 1, 'selected': False, 'text': '<p>My first action would be as follows:</p>\n\n<ol>\n<li>Build the binaries in "Release" version but creating debug info file (you will find this possibility in project settings).</li>\n<li>Use Dr Watson as a defualt debugger (DrWtsn32 -I) on a machine on which you want to reproduce the problem.</li>\n<li>Repdroduce the problem. Dr Watson will produce a dump that might be helpful in further analysis. </li>\n</ol>\n\n<p>Another try might be using WinDebug as a debugging tool which is quite powerful being at the same time also lightweight. </p>\n\n<p>Maybe these tools will allow you at least to narrow the problem to certain component.</p>\n\n<p>And are you sure that all the components of the project have correct runtime library settings (C/C++ tab, Code Generation category in VS 6.0 project settings)?</p>\n'}, {'answer_id': 3329, 'author': 'Michal Sznajder', 'author_id': 501, 'author_profile': 'https://Stackoverflow.com/users/501', 'pm_score': 3, 'selected': False, 'text': '<p>I have same problems in my work (we also use <code>VC6</code> sometimes). And there is no easy solution for it. I have only some hints:</p>\n\n<ul>\n<li>Try with automatic crash dumps on production machine (see <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=e089ca41-6a87-40c8-bf69-28ac08570b7e&amp;displaylang=en" rel="noreferrer">Process Dumper</a>). My experience says Dr. Watson is <strong>not perfect</strong> for dumping.</li>\n<li>Remove all <strong>catch(...)</strong> from your code. They often hide serious memory exceptions.</li>\n<li>Check <a href="https://rads.stackoverflow.com/amzn/click/com/0321374460" rel="noreferrer" rel="nofollow noreferrer">Advanced Windows Debugging</a> - there are lots of great tips for problems like yours. I recomend this with all my heart.</li>\n<li>If you use <code>STL</code> try <code>STLPort</code> and checked builds. Invalid iterator are hell.</li>\n</ul>\n\n<p>Good luck. Problems like yours take us months to solve. Be ready for this...</p>\n'}, {'answer_id': 22847, 'author': 'Mat Noguchi', 'author_id': 1799, 'author_profile': 'https://Stackoverflow.com/users/1799', 'pm_score': 1, 'selected': False, 'text': '<p>So from the limited information you have, this can be a combination of one or more things:</p>\n\n<ul>\n<li>Bad heap usage, i.e., double frees, read after free, write after free, setting the HEAP_NO_SERIALIZE flag with allocs and frees from multiple threads on the same heap</li>\n<li>Out of memory</li>\n<li>Bad code (i.e., buffer overflows, buffer underflows, etc.)</li>\n<li>"Timing" issues</li>\n</ul>\n\n<p>If it\'s at all the first two but not the last, you should have caught it by now with either pageheap.exe.</p>\n\n<p>Which most likely means it is due to how the code is accessing shared memory. Unfortunately, tracking that down is going to be rather painful. Unsynchronized access to shared memory often manifests as weird "timing" issues. Things like not using acquire/release semantics for synchronizing access to shared memory with a flag, not using locks appropriately, etc.</p>\n\n<p>At the very least, it would help to be able to track allocations somehow, as was suggested earlier. At least then you can view what actually happened up until the heap corruption and attempt to diagnose from that.</p>\n\n<p>Also, if you can easily redirect allocations to multiple heaps, you might want to try that to see if that either fixes the problem or results in more reproduceable buggy behavior.</p>\n\n<p>When you were testing with VS2008, did you run with HeapVerifier with Conserve Memory set to Yes? That might reduce the performance impact of the heap allocator. (Plus, you have to run with it Debug->Start with Application Verifier, but you may already know that.)</p>\n\n<p>You can also try debugging with Windbg and various uses of the !heap command.</p>\n\n<p>MSN</p>\n'}, {'answer_id': 22912, 'author': 'Graeme Perrow', 'author_id': 1821, 'author_profile': 'https://Stackoverflow.com/users/1821', 'pm_score': 3, 'selected': False, 'text': '<p>We\'ve had pretty good luck by writing our own malloc and free functions. In production, they just call the standard malloc and free, but in debug, they can do whatever you want. We also have a simple base class that does nothing but override the new and delete operators to use these functions, then any class you write can simply inherit from that class. If you have a ton of code, it may be a big job to replace calls to malloc and free to the new malloc and free (don\'t forget realloc!), but in the long run it\'s very helpful.</p>\n\n<p>In Steve Maguire\'s book <a href="http://www.microsoft.com/mspress/books/1024.aspx" rel="noreferrer">Writing Solid Code</a> (highly recommended), there are examples of debug stuff that you can do in these routines, like:</p>\n\n<ul>\n<li>Keep track of allocations to find leaks</li>\n<li>Allocate more memory than necessary and put markers at the beginning and end of memory -- during the free routine, you can ensure these markers are still there</li>\n<li>memset the memory with a marker on allocation (to find usage of uninitialized memory) and on free (to find usage of free\'d memory)</li>\n</ul>\n\n<p>Another good idea is to <em>never</em> use things like <code>strcpy</code>, <code>strcat</code>, or <code>sprintf</code> -- always use <code>strncpy</code>, <code>strncat</code>, and <code>snprintf</code>. We\'ve written our own versions of these as well, to make sure we don\'t write off the end of a buffer, and these have caught lots of problems too.</p>\n'}, {'answer_id': 26726, 'author': 'Ignas Limanauskas', 'author_id': 2877, 'author_profile': 'https://Stackoverflow.com/users/2877', 'pm_score': 2, 'selected': False, 'text': '<p>The apparent randomness of the memory corruption sounds very much like a thread synchronization issue - a bug is reproduced depending on machine speed. If objects (chuncks of memory) are shared among threads and synchronization (critical section, mutex, semaphore, other) primitives are not on per-class (per-object, per-class) basis, then it is possible to come to a situation where class (chunk of memory) is deleted / freed while in use, or used after deleted / freed.</p>\n\n<p>As a test for that, you could add synchronization primitives to each class and method. This will make your code slower because many objects will have to wait for each other, but if this eliminates the heap corruption, your heap-corruption problem will become a code optimization one.</p>\n'}, {'answer_id': 38809, 'author': 'Rob Walker', 'author_id': 3631, 'author_profile': 'https://Stackoverflow.com/users/3631', 'pm_score': 0, 'selected': False, 'text': "<p>Graeme's suggestion of custom malloc/free is a good idea. See if you can characterize some pattern about the corruption to give you a handle to leverage.</p>\n\n<p>For example, if it is always in a block of the same size (say 64 bytes) then change your malloc/free pair to always allocate 64 byte chunks in their own page.  When you free a 64 byte chunk then set the memory protection bits on that page to prevent reads and wites (using VirtualQuery).  Then anyone attempting to access this memory will generate an exception rather than corrupting the heap.</p>\n\n<p>This does assume that the number of outstanding 64 byte chunks is only moderate or you have a lot of memory to burn in the box!</p>\n"}, {'answer_id': 38911, 'author': 'Steve Steiner', 'author_id': 3892, 'author_profile': 'https://Stackoverflow.com/users/3892', 'pm_score': 2, 'selected': False, 'text': '<p>Is this in low memory conditions? If so it might be that new is returning <code>NULL</code> rather than throwing std::bad_alloc. Older <code>VC++</code> compilers didn\'t properly implement this.  There is an article about <a href="http://msdn.microsoft.com/en-us/magazine/cc164087.aspx" rel="nofollow noreferrer">Legacy memory allocation failures</a> crashing <code>STL</code> apps built with <code>VC6</code>.  </p>\n'}, {'answer_id': 70088, 'author': 'Tal', 'author_id': 11287, 'author_profile': 'https://Stackoverflow.com/users/11287', 'pm_score': 3, 'selected': False, 'text': '<p>Run the original application with <code>ADplus -crash -pn appnename.exe</code>\nWhen the memory issue pops-up you will get a nice big dump.</p>\n\n<p>You can analyze the dump to figure what memory location was corrupted.\nIf you are lucky the overwrite memory is a unique string you can figure out where it came from. If you are not lucky, you will need to dig into <code>win32</code> heap and figure what was the orignal memory characteristics. (heap -x  might help)</p>\n\n<p>After you know what was messed-up, you can narrow appverifier usage with special heap settings. i.e. you can specify what <code>DLL</code> you monitor, or what allocation size to monitor.</p>\n\n<p>Hopefully this will speedup the monitoring enough to catch the culprit.</p>\n\n<p>In my experience, I never needed full heap verifier mode, but I spent a lot of time analyzing the crash dump(s) and browsing sources. </p>\n\n<p><strong>P.S:</strong>\nYou can use <a href="http://blogs.msdn.com/tess/archive/2008/05/21/debugdiag-1-1-or-windbg-which-one-should-i-use-and-how-do-i-gather-memory-dumps.aspx" rel="noreferrer">DebugDiag</a> to analyze the dumps.\nIt can point out the <code>DLL</code> owning the corrupted heap, and give you other usefull details.</p>\n'}, {'answer_id': 83323, 'author': 'Steve Hanov', 'author_id': 15947, 'author_profile': 'https://Stackoverflow.com/users/15947', 'pm_score': 0, 'selected': False, 'text': '<p>If you choose to rewrite new/delete, I have done this and have simple source code at:</p>\n\n<p><a href="http://gandolf.homelinux.org/~smhanov/blog/?id=10" rel="nofollow noreferrer"><a href="http://gandolf.homelinux.org/~smhanov/blog/?id=10" rel="nofollow noreferrer">http://gandolf.homelinux.org/~smhanov/blog/?id=10</a></a></p>\n\n<p>This catches memory leaks and also inserts guard data before and after the memory block to capture heap corruption. You can just integrate with it by putting #include "debug.h" at the top of every CPP file, and defining DEBUG and DEBUG_MEM.</p>\n'}, {'answer_id': 196176, 'author': 'Constantin', 'author_id': 20310, 'author_profile': 'https://Stackoverflow.com/users/20310', 'pm_score': 2, 'selected': False, 'text': '<p>You should attack this problem with both runtime and static analysis.</p>\n\n<p>For static analysis consider compiling with PREfast (<code>cl.exe /analyze</code>). It detects mismatched <code>delete</code> and <code>delete[]</code>, buffer overruns and a host of other problems. Be prepared, though, to wade through many kilobytes of L6 warning, especially if your project still has <code>L4</code> not fixed.</p>\n\n<p>PREfast is available with Visual Studio Team System and, <a href="http://www.cs.auckland.ac.nz/~pgut001/pubs/sal.html" rel="nofollow noreferrer">apparently</a>, as part of Windows SDK.</p>\n'}, {'answer_id': 380781, 'author': 'lsalamon', 'author_id': 47733, 'author_profile': 'https://Stackoverflow.com/users/47733', 'pm_score': 0, 'selected': False, 'text': '<p>The little time I had to solve a similar problem.\nIf the problem still exists I suggest you do this :\nMonitor all calls to new/delete and malloc/calloc/realloc/free.\nI make single DLL exporting a function for register all calls. This function receive parameter for identifying your code source, pointer to allocated area and type of call saving this information in a table.\nAll allocated/freed pair is eliminated. At the end or after you need you make a call to an other function for create report for left data.\nWith this you can identify wrong calls (new/free or malloc/delete) or missing.\nIf have any case of buffer overwritten in your code the information saved can be wrong but each test may detect/discover/include a solution of failure identified. Many runs to help identify the errors. \nGood luck.</p>\n'}, {'answer_id': 1206734, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Do you think this is a race condition?  Are multiple threads sharing one heap?  Can you give each thread a private heap with HeapCreate, then they can run fast with HEAP_NO_SERIALIZE.  Otherwise, a heap should be thread safe, if you're using the multi-threaded version of the system libraries.</p>\n"}, {'answer_id': 1514251, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>A couple of suggestions. You mention the copious warnings at W4 - I would suggest taking the time to fix your code to compile cleanly at warning level 4 - this will go a long way to preventing subtle hard to find bugs.</p>\n\n<p>Second - for the /analyze switch - it does indeed generate copious warnings. To use this switch in my own project, what I did was to create a new header file that used #pragma warning to turn off all the additional warnings generated by /analyze. Then further down in the file, I turn on only those warnings I care about. Then use the /FI compiler switch to force this header file to be included first in all your compilation units. This should allow you to use the /analyze switch while controling the output</p>\n'}]
['https://Stackoverflow.com/questions/1069', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257/']