Life after free?

Jeffrey T. Hutzelman jh4o+ at andrew.cmu.edu
Sat Sep 29 03:02:43 AEST 1990


norm at oglvee.UUCP (Norman Joseph) writes:

> In <quan.654410256 at sol> quan at sol.surv.utas.oz (Stephen Quan)
> writes:
>
>>char *funny(ch)
>>char ch;
>>{
>>  char *tmp;
>>  [...]
>>  return tmp;
>>}
>
>>Any comments on free-ing tmp before it is return-ed?
>
> No, but I -do- have a comment on returning tmp at all.  The storage
>class in the declaration of tmp defaults to "auto".  This gives the
> variable tmp a number of important properties, one of which is
> dynamic duration.  Dynamic duration means that tmp only "exists"
> while the function in which it is declared is executing.  After
returning
> from the function, there is no guarantee about the value of the now
> non-existent variable tmp.
>
> If you want the variable tmp to retain its value between calls to the
> function, declare the variable as "static char *tmp".

Perhaps you want to reconsider that statement.  He is returning the
VALUE of tmp, not a pointer to it.  The value of a local (i.e. auto)
variable can be returned from a function even though the variable no
longer exists once the function returns.  Now if he had been returning
&tmp, that would have been different.  Note that even if he malloc'ed
memory and placed the pointer in tmp, he could safely return(tmp), and
the pointer would be returned and would point to the still-existent area
of memory.  As long as he didn't free(tmp) first, which would be
extraordinarily BAD.
-----------------
Jeffrey Hutzelman
America Online: JeffreyH11
Internet/BITNET:jh4o+ at andrew.cmu.edu, jhutz at drycas.club.cc.cmu.edu

>> Apple // Forever!!! <<



More information about the Comp.lang.c mailing list