Life after free?

bilbo at bisco.kodak.com bilbo at bisco.kodak.com
Wed Oct 3 00:33:44 AEST 1990


> 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?

GAG!  CHOKE!  COUGH!         1/2 :-)

I'd say you might get lucky if the calling function copied the result out
of the "buffer" IMMEDIATELY (i.e., in the very next statement) after the
return.  Most machines wouldn't have destroyed it by that time, but I wouldn't
guarantee ANYTHING.

This looks like the (BROKEN) code I've seen many times:

char *
foobar()
{
	char x[100];  			/*  NOTE: this is an AUTOMATIC variable	*/

	/* put something in x[] */

	return x;
}

Note that, since x is on the stack, it MIGHT not get blown away until after
you have a chance to move it somewhere, but don't bet your life on it!


--
Chuck Tryon
    (PLEASE use this address, as Kodak foobars one in header!)
    <bilbo at bisco.kodak.com>
    USmail: 46 Post Ave.;Roch. NY 14619                       B. Baggins
    <<...include standard disclamer...>>                      At Your Service

     "Then again, squirrels could be stupid."   (D. Mocsny)



More information about the Comp.lang.c mailing list