[comp.lang.c] Debugging versions of malloc and free

barmar@think.COM (Barry Margolin) (09/17/89)

In article <11089@smoke.BRL.MIL> gwyn@brl.arpa (Doug Gwyn) writes:
]In article <7513@bunker.UUCP> garys@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@think.com
{uunet,harvard}!think!barmar

tneff@bfmny0.UU.NET (Tom Neff) (09/17/89)

Hey, come on -- ANSI conformance should be a tool, not an obsession.  So
what if someone's DEBUG version of a program isn't conformant because it
plugs in a custom malloc().  Big deal!  You're not going to distribute
that version to mere users anyway.  Even if it would be nice to allow
other platforms to run it ("you say P:Squib 2.3 blew up with memory
error 5?  OK, rebuild it with -Dmalloc=mymalloc and mail me the output")
it's just a luxury, not an absolute requirement.  You do it where you
can get away with it (which will be plenty) and write off the rest.
-- 
'We have luck only with women --    \\\     Tom Neff
          not spacecraft!'         *-((O    tneff@bfmny0.UU.NET
 -- R. Kremnev, builder of FOBOS      \\\   uunet!bfmny0!tneff (UUCP)