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: abowers@gate.net (Al Bowers) Subject: Re: How do you release memory back to the kernel in C Date: 1998/05/24 Message-ID: <3568459a.8384137@news.gate.net>#1/1 X-Deja-AN: 356100760 References: <35616C36.9167165F@citicorp.com> <35620a04.2342689789@207.126.101.81> Organization: CyberGate, Inc. Newsgroups: comp.unix.osf.osf1,comp.lang.c On Wed, 20 May 1998 17:40:20 GMT, engebret@sg1.cr.usgs.gov (Chris Engebretson) wrote: >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: I don't see a smiley so I will make a few remarks. > > void progressive_free(void *ptr, size_t size) > { > size_t i; > > for(i = size - 1; i >= 1; --i) Why size - 1, You make get unexpedted results should the argument value of size be 0.. > ptr = realloc(ptr, i); > free(ptr); Why use free(). You can let realloc() do all the work. for(i = size; ;i--) { ptr = realloc(ptr,size); if(i== (size_t)0) break; } > } > >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.) As long as size accurately represents the size of the object, you can use this technique to almost totally verify that the pointer has been freed. #include #include #define ALLOC 10000 int FREE(void *p,size_t size); int main(void) { char *s = malloc(ALLOC); if(s == NULL) exit(EXIT_FAILURE); if(FREE(s,ALLOC)) { puts("Allocation most likely freed"); s = NULL; } else { puts("Allocation was not freed"); exit(EXIT_FAILURE); } return 0; } int FREE(void *p,size_t size) { size_t i; void *temp; for(i = size ; ;--i) { temp = realloc(p,i); if(i == (size_t)0) return 1; if(temp == NULL) return 0; p = temp; } } Al Bowers Tampa, FL mailto: abowers@combase.com http://www.gate.net/~abowers/index.html