Memory again...

Disclaimer: A different "Memory" than the previous post...

M
emory errors are a nightmare for every developer using a heapalloc. A good way to deal with these nightmares is Page heap verification.

PageHeap utility returns a pointer to allocated memory on 8 byte boundaries. The end of the returned pointer is followed by 0 to 7 guard bytes (depending on the size requested, 0 to 7 bytes are added to round up the request size to be on an 8 byte boundary), followed by a memory page marked PAGE_NOACCESS

For example:

char * p;
p = new char[5];

PageHeap returns a pointer to the 5 bytes plus 3 guard bytes to make up a total of 8 bytes, such as .....XXX . If the memory allocation size is a multiple of eight, there are no guard bytes added to the returned pointer.If the end of the allocation is overwritten, the guard bytes change and PageHeap causes an Access Violation (AV) when the memory is freed. If the application reads or writes past the allocation (including the guard bytes), it incurs an instant AV.


PAGE HEAP VERIFICATION USING GFlags.exe (with windbg).

A full heap verification for an application could be done using

gflags.exe -p /enable /full


This will automatically monitor all the malloc, new and heapalloc allocations made in the application. And in cases of memory errors, the application will crash with an exception

The exception Breakpoint A breakpoint has been reached. (0x80000003) occurred in the application at location 0x77f9f9df.

This should enable us to locate the point of crash in the code.

To disable page heap verification
gflags.exe -p /disable

For more information:
http://support.microsoft.com/default.aspx?scid=kb;en-us;286470
http://www.osronline.com/ddkx/ddtools/gflags_00s3.htm

Note: On Windows 2008 the memory manager itself takes care of this. So another way to locate memory errors in your module is to execute the same app on Windows 2008 :)

HTH