Life after free?

Paul John Falstad pfalstad at tan.Princeton.EDU
Sat Sep 29 02:42:50 AEST 1990


In article <60726 at iuvax.cs.indiana.edu>, bomgard at iuvax.cs.indiana.edu (Tim Bomgardner) writes:
|> In article <606 at oglvee.UUCP> 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;
...
|>     tmp = (char *) malloc(100);
...
|>     free(tmp);
|> }>  return tmp;
|> }>}
|> }If you want the variable tmp to retain its value between calls to the
|> }function, declare the variable as "static char *tmp".

True, but irrelevant.  The value returned is a pointer to an area of memory
returned by malloc(), which does not go away until you either free it
explicitly or exit the program.  The four bytes of space on the stack where
that value is kept will go away when funny returns, but funny will return
a copy of it in a register variable, so who cares?

|> Concerning tmp, there are three values which might be of interest:
|> 1) tmp: the value is the address of a char
|> 2) *tmp: the value is a char
|> 3) &tmp: the value is the address of variable tmp (likely in a stack frame)
|> 
|> After the malloc, tmp contains the address of a char (likely somewhere in
|> the heap, but it doesn't really matter as long as it isn't in the stack
|> frame for this function, which it won't be).  It is also true that
|> the next 99 addresses also contain chars, but that doesn't matter as far as
|> tmp is concerned.  After free(tmp), tmp may or may not contain that address,
|> and the contents of that address may or may not be changed.  But assume 
|> everything remains intact.  The function returns the VALUE of tmp, not its
|> address, and the calling function then has a pointer to 100 consecutive
|> chars.

Exactly.

|> It's obvious to almost everyone the dangers of continuing to use a pointer
|> to freed memory, but could someone explain to me why tmp's being an auto
|> variable is in any way relevant to the original question?

Certainly.  It isn't.
-- 
Here is the address to complain to:
pfalstad at phoenix.princeton.edu PLink:HYPNOS GEnie:P.FALSTAD CIS: 70016,1355
That address again,
sync at thumper.princeton.edu PLink:OHS738 GEnie:OHS738 CIS: 4128 143 1234 937



More information about the Comp.lang.c mailing list