February 20, 2011

Consider you are developing a C program for payroll system. You have declared an array of 50 integers to store employee numbers. C compiler will automatically reserve 100 bytes of memory. Because data type is integer and one integer takes 2 bytes. But at the runtime of program, you have stored information for 30 employees only. That means, you are wasting 40 bytes of Memory. Or, it may happen, you want to store information for more than 50 Employees. In that case, you can not increase the array size at run time.

Don’t worry. C has solution for this problem also – Dynamic memory allocation! You can allocate memory space at the runtime from free space. There are some standard library functions in C, which allows you to allocate and de‐allocate memory space,malloc(), calloc(), realloc() and free() are important ones.
We will see now how these functions works

Function

Task

malloc

The function malloc() is used to allocate a block of memory from the free space.

calloc

Same as malloc but it requires 2 argument. 1st is number of variables and 2nd is size required for each variable.