Subject: free()
To: None <netbsd-users@netbsd.org>
From: Erik Huizing <huizing@cpsc.ucalgary.ca>
List: netbsd-users
Date: 02/18/2001 21:44:33
How often are memory blocks marked by free() actually freed?

After noticing one of my programs seemed to be accumulating memory, even
though I knew I was freeing it as it ran. So I wrote a small program,
which allocates a chunk of memory, uses it and frees it. I've watched what
happens on top, and the memory doesn't appear to get freed until the
program exists. 'ps' tells me the same story:

USER       PID %CPU %MEM   VSZ  RSS TT  STAT STARTED       TIME COMMAND
erik      5368  0.0  0.8   164  508 p2  S+    9:26PM    0:00.04 foo
erik      5368 12.8 30.8 32936 20056 p2  S+    9:26PM    0:01.29 foo
after printing 'freed', I still get this:
erik      5368  2.1 30.8 32936 20056 p2  S+    9:26PM    0:01.29 foo

Is there a way to have the memory I'm freeing be released without needing
my program to exit?

This was the gist my program:

int main(int ac, char **av) {
   void *mem;
   printf("starting\n"); sleep( 7 );

   printf("allocating memory\n");

   mem = malloc( SIZE );     memset( mem, 0, 20000000 );
   printf("allocated!\n");   sleep( 7 );

   free( mem );
   printf("freed!\n");       sleep( 60 );
   return 0;
}
The first rule of Fight Club is You Do Not Talk About Fight Club.

// Erik Huizing   huizing@cpsc.ucalgary.ca
// www.cpsc.ucalgary.ca/~huizing