realloc() Problems
The realloc() function can either extend a current memory block, or create a new block and free the old. When it creates a new block, it can create problems. Although you can check to see which action occurred, you need to code realloc() usage defensively so that problems do not occur. Specifically, you must change every pointer pointing to the memory block that was reallocated so that it points to the new one. Also, if the pointer doesn’t point to the beginning of the block, you need to take some corrective action.
In
Figure 172, two pointers are pointing to a block. After the
realloc() function executes,
ptr1 points to the new block. However,
ptr2 still points to the original block, a block that a program deallocated and returned to the heap manager.
If you use block painting (See
Example: Viewing Painted Memory), TotalView can initialize the first block with a bit pattern. If your program is able to display the contents of this block to you, you’ll be able to see what kind of problem occurred.