View Full Version : Why realloc() has problems.

07-20-2006, 08:51 AM
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.[br] [/url]
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.[br] http://www.etnus.com/Documentation/latest/html/TotalView_Tips/images/realloc_issues.jpg

The follow simple example illustrates thsi problem. Here is a snapshot of a small program that allocates some memory, sets a couple of values within the memory, and then reallocates the region:


[/url]The following sequence the value of the [b]p and q pointers as the program executes. (The program was compiled using gcc on a computer running the Red Hat Linux operating system.) Below each screen shot of the Expression List window is a description of what you are seeing. The line numbers in this column are those shown in the program snapshot.

Line 8: Immediately before the pointer p is initialized to the memory returned by malloc(). [/url]

Line 9: Immediately after a memory block is allocated and assigned to p. Notice that the memory location is 0x80496b8. [/url]

Line 11: Immediately after the first set of bytes is initialized to 2. [/url]

Line 12: Immediately after the pointer p is incremented to point to the next integer location. The memory location is now 0x80496bc. [/url]

Line 13: Immediately after the second set of bytes is initialized to 4. [/url]

Line 14: Immediately after pointer q is set to be equal to pointer p. [/url]

Line 15: Immediately after pointer p is decremented so that it again points to the beginning of the block. [/url]

Line 17: Immediately after the block pointed to by p is reallocated. The value of p is now 0x401c4008. Notice that the memory manager has copied the memory values contained in the old block. [/url]

Line 18: After the pointer p is incremented. It now points to an integer 4 value after. q, however, is pointing to a different memory location that also contains a value of 4. [/url]

Line 19: After the second integer value in the reallocated memory block is set to 10. At this time, p and q are different. [/url]

Line 20: After adding the offset calculated in line 15 to p and setting that value to q. Both pointers again point to the same memory location.