effect of free()

Engineering scott at bbxeng.UUCP
Thu Aug 24 02:19:11 AEST 1989


In article <572 at augean.OZ>  writes:
>In article <14343 at haddock.ima.isc.com> karl at haddock.ima.isc.com (Karl Heuer) writes:
>>In article <568 at augean.OZ> Ian Dall writes:
>>>In article <1989Aug17.005548.745 at twwells.com> bill at twwells.com (T. William Wells) writes:
>>>>	free(ptr);
>>>>	if (ptr == 0) ...
>>>>The if might cause a trap when the value of ptr is accessed.
>>The issue is not whether the value of ptr has changed.  Some architectures
>>distinguish between arithmetic registers and address registers, and refuse to
>>allow arbitrary garbage to be loaded into an address register.
>
>"free" or ANY function cannot change it's argument. "free" should not load
>anything into "the special address register" (let alone "arbitrary garbage").
>

What the earlier poster was trying to say is that the block of memory
pointed to by ptr might have been deallocated by free() and no longer
part of the process's memory map.  It is possible that the mere access
to ptr in the 'if' statement could cause a trap.  This seems unlikely to
me since one should be expected to be able to compare pointers without
worry.  What bugs me about the example is passing a pointer to free() and
*then* testing it.  If there was a possibility that ptr==0 then it should
be checked first.  A glance at the Xenix programmers reference manual
shows that there are *two* malloc libraries.  One of them destroys a
freed memory block while the other doesn't.  Both libraries say that
free() should only be passed a pointer returned by malloc().  Since
malloc() can return a 0 then it follows that free() will handle a 0
argument.  I personally prefer to avoid tempting Murphy's Law in these
situations.  It's too easy to get burned.

-- 

---------------------------------------
Scott Amspoker
Basis International, Albuquerque, NM
505-345-5232



More information about the Comp.lang.c mailing list