Simple heap corruption example

Question: Take a simple heap corruption example in C/C++

Answer:

Heap corruption can occur from various reasons such as double free (freeing a pointer twice), old pointer reuse (reusing a pointer after freed), buffer overrun (writing beyond buffer's boundary).

The following code will raise heap corruption because of double free.

// heap corruption due to double free

#include 

char* mem = NULL;

int main(int argc, char* argv[])
{
    mem = (char*)malloc(10 * sizeof(char));
    mem[0] = 'A';

    free(mem);
    free(mem); // double free
}

When running the debug build in WinDbg, "Invalid address specified to RtlValidateHeap" error will be thrown as first chance exception.

0:000> g
HEAP[heaptest.exe]: Invalid address specified to RtlValidateHeap( 009E0000, 009F4808 )
(3a60.3d78): Break instruction exception - code 80000003 (first chance)
eax=00779000 ebx=009f4800 ecx=009e4d44 edx=0098f431 esi=009e0000 edi=009e0000
eip=77728c59 esp=0098f598 ebp=0098f5a4 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202
ntdll!RtlpValidateHeapEntry+0x61d14:
77728c59 cc              int     3

0:000> g
Debug Assertion Failed!

Program: C:\src\heaptest\Debug\heaptest.exe
File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
Line: 904

Expression: _CrtIsValidHeapPointer(block)
...