Why using realloc() can cause problems

 

The realloc() function can create unanticipated problems. This function can either extend a current memory block, or create a new block and free the old. Although you can check to see which action occurred, you need to code defensively so that problems do not occur. Specifically, you must change every pointer pointing to the memory block to point to the new one. Also, if a pointer doesn't point to the beginning of the block, you need to take corrective actions.

In the following figure, 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 was deallocated and returned to the heap manager. It is now a dangling pointer.


You can find tips that we've already sent out in our Tip Archive

Help us improve these tips!