Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!rutgers!njin!princeton!tan.Princeton.EDU!pfalstad From: pfalstad@tan.Princeton.EDU (Paul John Falstad) Newsgroups: comp.lang.c Subject: Re: Life after free? Keywords: free malloc Message-ID: <2909@idunno.Princeton.EDU> Date: 28 Sep 90 16:42:50 GMT References: <606@oglvee.UUCP> <60726@iuvax.cs.indiana.edu> Sender: news@idunno.Princeton.EDU Reply-To: pfalstad@tan.Princeton.EDU (Paul John Falstad) Lines: 50 In article <60726@iuvax.cs.indiana.edu>, bomgard@iuvax.cs.indiana.edu (Tim Bomgardner) writes: |> 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; ... |> tmp = (char *) malloc(100); ... |> free(tmp); |> }> return tmp; |> }>} |> }If you want the variable tmp to retain its value between calls to the |> }function, declare the variable as "static char *tmp". True, but irrelevant. The value returned is a pointer to an area of memory returned by malloc(), which does not go away until you either free it explicitly or exit the program. The four bytes of space on the stack where that value is kept will go away when funny returns, but funny will return a copy of it in a register variable, so who cares? |> 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. Exactly. |> 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? Certainly. It isn't. -- Here is the address to complain to: pfalstad@phoenix.princeton.edu PLink:HYPNOS GEnie:P.FALSTAD CIS: 70016,1355 That address again, sync@thumper.princeton.edu PLink:OHS738 GEnie:OHS738 CIS: 4128 143 1234 937