Life after free?

Tim Bomgardner bomgard at iuvax.cs.indiana.edu
Sat Sep 29 02:03:06 AEST 1990


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;
    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?
}
}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".

I doubt that anyone on the net is better than I am at missing the obvious,
especially when it's right in front of my face, but this doesn't make much
sense to me.  The part about auto variables is true, but that has nothing
to do with returned values.

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.

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?



More information about the Comp.lang.c mailing list