Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!samsung!munnari.oz.au!diemen!sol!quan From: quan@sol.surv.utas.oz (Stephen Quan) Newsgroups: comp.lang.c Subject: Why 'life after free'. Keywords: question about malloc+free combination. Message-ID: Date: 30 Sep 90 05:52:26 GMT Sender: news@diemen.utas.edu.au Distribution: comp Lines: 44 Hi, I'm the original poster (stephen quan@sol.surv.utas.edu.au), and I wish to make some more comments on 'life after free'. From: wuxing@comp.mscs.mu.edu (Xing Wu) >In article 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@sol.surv.utas.edu.au