Wednesday, January 30, 2013

Why a process's memory usage won't decrease after being freed?

I'm using OS X and use Activity Monitor to check the memory usage of my program. However, this may fool people to think that their programs have memory leakages.

Let's check this example.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

struct list {
  char data[1024];
  struct list *next;
};

int main(int argc, char *argv[])
{
  sleep(5);

  /* Consume some memory  */
  struct list *head = malloc(sizeof(struct list));
  
  int i = 300;
  struct list *p = head;
  while (i-->0) {
    p->next = malloc(sizeof(struct list));
    p = p->next;
  }
 
  printf("Consumed a lot memory. Wait 5s to free them\n");

  sleep(5);

  i = 300;
  while (i-->0) {
    p = head->next;
    free(head);
    head = p;
  }

  printf("freed, wait 10s to exit\n");
  sleep(10);

  return 0;
}

Open your Activity Monitor and filter out your program, you will see that at first stage, the program costs about 150kb, then about 500kb after five seconds. After freeing the memory, you can see that the program still costs 500kb.

Why is this happening?

Put simply, the memory malloc'ed is granted to your process and won't return to OS immediately after you call free. The freed memory can be used later by the process.

A little more detail: http://stackoverflow.com/questions/447899/why-does-my-c-program-not-free-memory-as-it-should/447932#447932

No comments:

Post a Comment