From mboxrd@z Thu Jan 1 00:00:00 1970 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: fee84,cea30133e185dc3 X-Google-Attributes: gidfee84,public X-Google-Thread: 1014db,cea30133e185dc3 X-Google-Attributes: gid1014db,public From: engebret@sg1.cr.usgs.gov (Chris Engebretson) Subject: Re: How do you release memory back to the kernel in C Date: 1998/05/20 Message-ID: #1/1 X-Deja-AN: 355023789 Sender: news@igsrsparc2.er.usgs.gov (Janet Walz (GD) x6739) X-Nntp-Posting-Host: sg1.cr.usgs.gov References: <35616C36.9167165F@citicorp.com> <35620a04.2342689789@207.126.101.81> Organization: Raytheon STX Corporation Reply-To: engebret@sg1.cr.usgs.gov Newsgroups: comp.unix.osf.osf1,comp.lang.c In article <35620a04.2342689789@207.126.101.81>, kaz@cafe.dot.net (Kaz Kylheku) writes: |> On Tue, 19 May 1998 12:25:42 +0100, |> Asgar Ali wrote: |> |> >In DEC Unix (3.x and 4.x) I am finding that "free" does not release |> >memory back to the kernel so that it could be used by other processes. |> |> See Peter Seebach's Infrequently Asked Questions list: |> |> 6.9: I have a program which mallocs but then frees a lot of memory, |> but memory usage (as reported by ps) doesn't seem to go back down. |> |> You're probably not freeing the memory completely. Try replacing |> |> free(foo); |> |> with |> |> free(foo); |> free(foo); |> free(foo); |> |> in case the first free() frees the memory only partially. (Unix wizards |> may recognize the parallel with syncing three times before rebooting.) This generally works (well, better than a single bare free(), that is) but there are more robust ways to successfully free memory. Some Unices have a difficult time freeing large chunks of memory, and even the triple-free() approach above doesn't always work. What I generally recommend is freeing the block one byte at a time: void progressive_free(void *ptr, size_t size) { size_t i; for(i = size - 1; i >= 1; --i) ptr = realloc(ptr, i); free(ptr); } This gradually chops the block down to a single byte, which most implementations of free() handle quite nicely. (Note the obvious safety defect in that the return of realloc() is not checked and the original pointer value is not preserved; sanity checking is left as an exercise to the reader.) Regards, -- Chris Engebretson - Raytheon STX Corporation | Ph#: (605)594-6829 USGS EROS Data Center, Sioux Falls, SD 57198 | Fax: (605)594-6940 http://edcwww.cr.usgs.gov/ mailto:engebret@sg1.cr.usgs.gov Opinions are not those of Raytheon Systems Company or the USGS.