PDA

View Full Version : Why is using realloc() frowned upon?



Barry-TotalView-Tech
02-04-2007, 06:26 AM
It's frowned upon because it can create unanticipated problems. When a variable's memory is reallocated, the malloc library can either extend the current memory block or it can 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 so that it points to the new one. Also, if a pointer doesn't point to the beginning of the block, you need to move it to the corresponding place in the new block.

The top part of the following figure shows two pointers pointing to a block. After a realloc() function executes based on ptr1, 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.