Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!mailrus!iuvax!bomgard From: bomgard@iuvax.cs.indiana.edu (Tim Bomgardner) Newsgroups: comp.lang.c Subject: Re: Life after free? Keywords: free malloc Message-ID: <60726@iuvax.cs.indiana.edu> Date: 28 Sep 90 16:03:06 GMT References: <606@oglvee.UUCP> Organization: Indiana University, Bloomington Lines: 52 In article <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; 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?