Why 'life after free'.

Stephen Quan quan at sol.surv.utas.oz
Sun Sep 30 15:52:26 AEST 1990


Hi, I'm the original poster (stephen quan at sol.surv.utas.edu.au), and I
wish to make some more comments on 'life after free'.

From: wuxing at comp.mscs.mu.edu (Xing Wu)
>In article <quan.654410256 at sol> you write:
>>  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?
>
>You mean, other than "why?"

>According to my manpage, free makes the space "available for further
>allocation, but its contents are undisturbed."
>
>This would lead me to believe that, depending on the compiler, and
>depending on your OS, and depending on the phase of the moon, the 
>pointer would still point to the buffer you malloc'ed.  Maybe.

I interpreted the MAN page just the same.  However, I was hoping that the
man page implied that the memory contents is still valid for at least one
instruction more.  Why?  I'll tell you in a sec ...

>Is there any particular reason you don't return the pointer, use
>it, and then free it?

I normally do what you suggest, the reason why a brought up this issue is
that if what I propose wasn't so unpredictable then I can have something
like :

  printf("%s\n",funny('c'));
  printf("%s\n",funny('x'));

Where funny will create a string of 100 c's or 100 s's.  The string is
displayed in 'printf' (hopefully) and you don't need to worry about
free-ing the memory.

(For keen programmers, the C definition for funny up-up above is not quite
 correct, but I think you get the picture, anyway.  ie missing 0 string
 terminator.).

stephen quan at sol.surv.utas.edu.au



More information about the Comp.lang.c mailing list