title: How can I debug heap errors in a C# class library?
body: <p>I'm getting a heap corruption error in a C# library module I'm calling through COM in a C++ app. The specific error is:</p>
  
  <blockquote>
    <p>HEAP: Free Heap block 4b61bb8 modified
    at 4b61be8 after it was freed<BR>
    ...<BR> This may be due to a
    corruption of the heap, and indicates
    a bug in [app].exe
    or any of the DLLs it has loaded.</p>
  </blockquote>
  
  <p>The top of the call stack is:</p>
  
  <pre><code>CustomMarshalers.dll!System.Runtime.InteropServices.CustomMarshalers.EnumeratorViewOfEnumVariant.MoveNext() + 0x168 bytes
  </code></pre>
  
  <p>Now my understanding was that .NET was supposed to mitigate memory problems, not make more memory problems with were impossible to fix. Yet, I can't think of anything which I might be doing to cause a memory error, or how I would possibly go about trying to fix it. The particular module is using the Microsoft.VisualStudio.VCProjectEngine .NET components to iterate VC project files, with pretty simple iterators. It's breaking in a foreach statement while iterating Files in a VCProject filter (folder), after succeeding for the previous about 100 calls. The actual code which is breaking is:</p>
  
  <pre><code>    IVCCollection CollectionFiles = (IVCCollection)FolderInProject.Files;
      foreach (VCFile File in CollectionFiles)
      {
          [...]
      }
  </code></pre>
  
  <p>How can I possibly go about debugging this?</p>
  
  <p>Update:</p>
  
  <p>When I call if from a pure C# Console app (no COM or native code involved), I get:</p>
  
  <blockquote>
    <p>An unhandled exception of type
    'System.AccessViolationException'
    occurred in [component].dll<BR>
    <BR>
    Additional
    information: Attempted to read or
    write protected memory. This is often
    an indication that other memory is
    corrupt.</p>
  </blockquote>
  
  <p>Still no clue how I could go about debugging this. Obviously there's a memory error happening somewhere... but how can I track it down in pure managed code where the memory model isn't even exposed?</p>