Why realloc() has problems, revisited

 

This tip has many graphics. It may load slowly.

A tip-of-the-week reader asked for clarification on the reallocation information presented in a previous tip. That tip talked about manipulating pointers that point into a memory block that will be reallocated.

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:

In the following table, the column on the left contains an Expression List Window that shows the value of the p and q pointers as the program executes. (The program was compiled using gcc on a computer running the Red Hat Linux operating system.) The column on the right describes what you are seeing. The line numbers in this column are those shown in the program snapshot.

Expression List Window
Location and Explanation




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




Line 9: Immediately after a memory block is allocated and assigned to p. Notice that the memory location is 0x804a008.




Line 11: Immediately after the first set of bytes is initialized to 2.




Line 12: Immediately after the pointer p is incremented to point to the next integer location. The memory location is now 0x804a00c.




Line 13: Immediately after the second set of bytes is initialized to 4.




Line 14: Immediately after pointer q is set to be equal to pointer p.




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




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




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.




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




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.


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

Help us improve these tips!