Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!samsung!sdd.hp.com!zaphod.mps.ohio-state.edu!julius.cs.uiuc.edu!psuvax1!rutgers!rochester!pt.cs.cmu.edu!o.gp.cs.cmu.edu!andrew.cmu.edu!jh4o+ From: jh4o+@andrew.cmu.edu (Jeffrey T. Hutzelman) Newsgroups: comp.lang.c Subject: Re: Life after free? Message-ID: Date: 28 Sep 90 17:02:43 GMT References: , <606@oglvee.UUCP> Organization: Carnegie Mellon, Pittsburgh, PA Lines: 42 In-Reply-To: <606@oglvee.UUCP> norm@oglvee.UUCP (Norman Joseph) writes: > In quan@sol.surv.utas.oz (Stephen Quan) > writes: > >>char *funny(ch) >>char ch; >>{ >> char *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". Perhaps you want to reconsider that statement. He is returning the VALUE of tmp, not a pointer to it. The value of a local (i.e. auto) variable can be returned from a function even though the variable no longer exists once the function returns. Now if he had been returning &tmp, that would have been different. Note that even if he malloc'ed memory and placed the pointer in tmp, he could safely return(tmp), and the pointer would be returned and would point to the still-existent area of memory. As long as he didn't free(tmp) first, which would be extraordinarily BAD. ----------------- Jeffrey Hutzelman America Online: JeffreyH11 Internet/BITNET:jh4o+@andrew.cmu.edu, jhutz@drycas.club.cc.cmu.edu >> Apple // Forever!!! <<