PDA

View Full Version : Using Guard Blocks (for detecting heap memory corruption)



Josh-TotalView-Tech
07-20-2006, 09:44 AM
After you allocate memory, it is your responsibility not to write data outside the allocated block. The Memory Debugger can help you detect these kinds of problems by surrounding memory allocations with a small amount of additional memory. These additional memory blocks are called guard blocks. If your program overwrites these blocks, the Memory Debugger can tell that a problem occurred. [/url]
You can tell that a problem occurred in two ways: [/url] When you are displaying a Heap Status view, you can ask for a Corrupted Guard Blocks View. The Heap Graphical view also shows the guard regions and corrupted blocks. [/url] When your program deallocates memory, the Memory Debugger can check the deallocated block's guards. If they've been violated�that is, if you're program has written data into them�the Memory Debugger can stop execution and alert you to the problem. [/url]
For example, suppose you allocate 16 bytes and you write 64 bytes of data. While the first 16 bytes are correctly written, the remaining 48 aren't. You will have overwritten the guard blocks for both blocks and some of the next block's data. That is, you will have inadvertently changed some data, data that when accessed will be incorrect.[br] [/url]
Using guard blocks to detect problems is usually an interactive process. Asking for notification when the block is deallocated lets you know that a problem has occurred. Because you now know where the block was corrupted, you can use this as a starting point to locate the cause of the problem. In many cases, you will rerun your program, focusing on those blocks. For example, you could set a watchpoint on the end of block the next time the block is allocated. (Do this by chasing the pointer that points to the beginning of the block, then casting the block into an array of $voids, then set it on the last element in the array.)[br] [/url]
You can step through your program and periodically ask the Memory Debugger to check the guards. This will help you locate where your program is corrupting data.