effect of free()

Mark Brader msb at sq.sq.com
Sat Sep 16 19:19:03 AEST 1989


This discussion belongs in comp.std.c by now, but as I think it ought
to be winding down, I won't trouble to redirect it.

> OK - then consider the following code fragment (no pointer/int flames,
> please - they're not relevant here):

Oh yes they are.  But I'll get to that in a moment.

> union pi {
>     char *ptr;
>     unsigned long num;
> } x;
> x.ptr = malloc(AMOUNT);
> if (x.ptr != NULL) free(x.ptr);
> foo(x.num);
> This is perfectly legal code (despite that x.num contains nothing of
> guaranteed usefulness) and any compiler that generates code that causes
> a seg fault on the call to foo() has some serious problems. 

Correct.  But that final statement doesn't necessarily access all the bytes
of x!  There's no guarantee that sizeof(unsigned long) >= sizeof(char *).

It might be the case that the only registers *large enough* to contain
pointers are those which also have the effect of trapping when loaded
with an invalid pointer value.  Then if you want to ensure that "if (ptr
== 0)" does not trap, you have to implement it in some more complicated
way that a simple register load and test.  For X3J11 to have required
such a time penalty just to save some programs that are broken anyway
would not have been reasonable.

For people coming in late, two things should be pointed out.  One is that
comparison involving a legitimately created null pointer is not at issue;
a machine such as just described can implement "if (ptr == 0)" in the
obvious way, without fear of trapping if ptr is a null pointer, by choosing
to implement null pointers as pointers to an allocated but otherwise unused
piece of actual memory.  Of course, the 0 is a null pointer constant in this
context and would be converted at compile time to such a pointer.

The second thing was in the article to which the one quoted above was
a response:
| The discussion was about what MIGHT legally occur in a C implementation
| on SOME architecture. 

-- 
Mark Brader, Toronto	"If the standard says that [things] depend on the
utzoo!sq!msb		 phase of the moon, the programmer should be prepared
msb at sq.com		 to look out the window as necessary."  -- Chris Torek

This article is in the public domain.



More information about the Comp.lang.c mailing list