February 20, 2011

Dynamic Memory Allocation in C


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.
free
Frees previously allocated space
realloc
Modifies the size of previously allocated space.



malloc() function
malloc - a memory allocator
Prototype:
stdlib.h
void *malloc(size_t size);

calloc() function
calloc - a memory allocator
Prototype:
stdlib.h
void *calloc(size_t num, size_t size);

realloc() function
realloc - memory reallocator
Prototype:
stdlib.h
void *realloc(void *ptr, size_t size);

free() function
free - free allocated memory
Prototype:
stdlib.h
void free(void *ptr);

Hope you like the post, give feedback by comments.. :)

Related Posts :



Categories:

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Related Posts with Thumbnails