detect heap corruption BEFORE garbage collect

Posted on 2011-10-30
Last Modified: 2013-12-16
Hello all,
I am using cdb/windbg to try to force a break when heap corruption occurs by pinvoke into ReadFile.  The debugger does not see the access violation until after GC.Collect, which is **too late** for me. Prior to running my program, i run "gflags -p /enable testheap.exe /unaligned"  The effect seems useless.  I wrote this little test program to apply what I find to debugging a larger commercial program that is having heap corruption issues.

I have also tried DebugDiag with Application Verifier and MDA callbackOnCollectedDelegate without success.  Please help, as I have been struggling with this issue for a long time.

namespace TestHeap
  public partial class Form1 : Form
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
      uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
      uint dwFlagsAndAttributes, IntPtr hTemplateFile);
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool ReadFile(SafeFileHandle hFile, [Out] byte[] lpBuffer,
       uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped);
    string fileName = "testHeap.txt";
    const uint GENERIC_READ = 0x80000000;
    const uint OPEN_EXISTING = 3;
    SafeFileHandle sh;
    byte[] chBuf = new byte[8];

    public Form1()

    private void testBtn_Click(object sender, EventArgs e)
      bool nStat;
      uint bytesToRead = 1025;
      uint bytesRead = 0;

      if (!(nStat = ReadFile( sh, chBuf, bytesToRead, out bytesRead, IntPtr.Zero)))
        Debug.Print("testBtn_Click error in ReadFile, nStat = {0}", nStat);
      MessageBox.Show(string.Format("After ReadFile, bytesToRead = {0},\n bytes read = {1}", bytesToRead, bytesRead));
      MessageBox.Show("testBtn_Click end, after GC.Collect");

    private void Form1_Load(object sender, EventArgs e)
      sh = CreateFile(fileName, GENERIC_READ, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

Open in new window

Question by:Tech_Dr
    LVL 11

    Expert Comment

    byte[] chBuf = new byte[8];

    IntPtr chBuf = Marshal.AllocHGlobal(8);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool ReadFile(SafeFileHandle hFile, [Out] IntPtr lpBuffer,
    uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped);

    Author Comment

    samir:  Your answer appears to be a cut-and-paste from my post on

    Accepted Solution

    Several months ago I solved my large project problem without using the techniques described in the original post. It seems that the corrupt heap state in native code can't communicate with managed code in a timely manner, at least not with the tools described above. I am updating this with the hope that it may help save someone a lot of time.

    The problem was found within my large project in a totally separate, unsuspected area: USB communication calls. Prior testing did not show any problems in this area. Nevertheless, I went through every single pinvoke call and substituted each call with an updated (third party) library call when possible. Also, I eliminated all "unsafe" pointer usage with alternatives.  Being that I had struggled with this for months, two or three days of inspecting all pinvoke calls was worth the effort.

    In Visual Studio 2010 I was able to verify that heap corruption no longer occured in my updated code by using the debugging extension sos.dll, and periodically making the !verifyheap call manually by hand.  All's well with the program now - no crashes, no heap corruption.

    Author Closing Comment

    No other suggestion worked. This did.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
    Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
    Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
    This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now