Life after free?

James C Burley burley at world.std.com
Sat Sep 29 19:07:23 AEST 1990


In article <5620 at stpstn.UUCP> lerman at stpstn.UUCP (Ken Lerman) writes:

   In article <quan.654410256 at sol> quan at sol.surv.utas.oz (Stephen Quan) writes:
   ->char *funny(ch)
   ->char ch;
   ->{
   ->  char *tmp;
   ->  int i;
   ->  
   ->  tmp = (char *) malloc(100);
   ->  for (i=0; i<=99 ; i++) *(tmp+i) = ch;
   ->  free(tmp);
   ->  return tmp;
   ->}
   ->
   ->Any comments on free-ing tmp before it is return-ed?
   ->
   ->Stephen Quan (quan at sol.surv.utas.edu.au)
   ->University of Tasmania.

   Not only is it sensible, the semantics of free require it.  The item
   freed is guaranteed to be valid until the next call to malloc,
   realloc, ...

To who or what do you refer when you say "The item freed is guaranteed to
be valid..."?  I think it's fair to assume such statement would refer either
to the First Edition K&R C book or the ANSI C standard.  I don't have a K&R
C I book (and of course my K&R C II is based on the ANSI C standard), but my
ANSI C standard has this to say at the end of the paragraph beginning section
4.10.3 "Memory management functions":

    "The value of a pointer that refers to free space is indeterminate."

Perhaps some implementations make such a guarantee; if you're referring to
one of those, it might be a good idea to qualify the comment accordingly.
If you're referring to K&R C I, and you also are correct, that surprises me
because I wasn't aware of that guarantee either in my early days of using
C or when I read the ANSI C standard and other articles on the dangerous
so-called "quiet changes" -- and it seems to me dropping such a guarantee
from K&R C I when creating ANSI C would constitute such a quiet change.

James Craig Burley, Software Craftsperson    burley at world.std.com



More information about the Comp.lang.c mailing list