Debugging versions of malloc and free (was Re: The free() thing)

Barry Margolin barmar at think.COM
Sun Sep 17 17:23:13 AEST 1989


In article <11089 at smoke.BRL.MIL> gwyn at brl.arpa (Doug Gwyn) writes:
]In article <7513 at bunker.UUCP> garys at bunker.UUCP (Gary M. Samuelson) writes:
]>Myfree() checks to make sure that
]>(1). the pointer I want to free() was one originally obtained by
]>mymalloc(), and (2) that it has not already been released by myfree().
]>I claim that this is a valid use for a pointer which no longer points
]>to anything.
]I too have implemented such a safety-checking malloc/free wrapper,
]and it seems to me that yours must be making a mistake.  You should
]be checking only that the pointer fed to myfree() is one CURRENTLY
]HANDED OUT by myalloc(), not that it has never previously been fed
]to myfree().  As you malloc/free/malloc/free/..., eventually the same
]pointer values come around again.  Having been previously freed does
]not mean that a pointer value is not currently being used correctly,
]because it may have been returned by a subsequent malloc().

A safe, portable way to write myfree() is to NOT have it call free().
Instead, it could just add the pointer to a list of freed pointers.
Future calls to myfree() could check whether the pointer is on the
free list.  Mymalloc will never return the same pointer twice.  This
scheme will work fine as long as it doesn't cause the process to run
out of virtual memory or swap space.

Barry Margolin
Thinking Machines Corp.

barmar at think.com
{uunet,harvard}!think!barmar



More information about the Comp.lang.c mailing list