Using Page Heap Verification to Locate Heap Allocation Bugs

The program code below has a heap overflow bug. The memory location referenced by lpHeapVar1 is allocated one byte, but the subsequent code attempts to fill it with ten bytes of data, thus overflowing it.

#include <stdlib.h>
#include <stdio.h>
#include <strings.h>

int main(int argc, char **argv) {
    char stackVar[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    char *lpHeapVar1, *lpHeapVar2;
    printf("before allocating heap 1\n");
    lpHeapVar1 = (char *) malloc(1);
    printf("after allocating heap 1\n");
    printf("before overflowing heap 1\n");
    memcpy(lpHeapVar1, &stackVar, 10); // heap overflow
    printf("after overflowing heap 1\n");
    // other code here
    printf("before allocating heap 2\n");
    lpHeapVar2 = (char *) malloc(1);
    printf("after allocating heap 2\n");
    return 0;

When the program code above is compiled and run, it will crash at the following line of code.

lpHeapVar2 = (char *) malloc(1);

However, there is nothing wrong with the second malloc call itself. This makes the bug difficult to track down, even if a heap overflow is suspected to be the cause, especially if many lines of code separate the point of overflow and the subsequent heap allocation.

Page heap verification can help to track down such bugs. GFlags (included with Debugging Tools for Windows) is used to enable page heap verification.

C:\> gflags.exe -p /enable heap_allocate.exe /full
path: SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
    heap_allocate.exe: page heap enabled

where heap_allocate.exe is the compiled executable file.

Subsequently, when the program is run, it will crash at the point of the heap overflow (the memcpy function call).




Leave a Comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s