Monday, April 20, 2009

Malloc, Calloc, etc

A user program requesting for a dynamically allocated memory uses a variant of malloc() for requesting memory. The malloc() is library call implemented in C-Library (most likely G-Lib-C). Malloc() takes care of the memory requirements of the program efficiently.

The simplest implementation of malloc() would be to invoke a system call everytime a process requests for memory and a system call when a process releases the memory. However this would be very expense because:
(1) system calls are computationally expensive.
(2) Too many memory regions means too much over head.

Thus the malloc functions implements some more intelligence. Whenever the process makes the first malloc request, the malloc translates it to a bigger memory request from the kernel. After this, the system call is not required for further memory requests as long as the memory allocated by the kernel is enough to satisfy the requests. Malloc function call manages the memory internally for the process.

The Malloc functions makes an internal decision when to invoke a system call for requesting or freeing up the memory. It also makes an internal decision whether to request a memory using brk() or mmap() system calls.

No comments: