Memory Management in C

In this article I would like to provide few tips related to memory management when we use C libraries malloc(), calloc() and free() functions.

Whenever possible, try to use static buffers where compiler automatically frees such memory. Make sure that, previously allocated memory is freed manually.

malloc():

The library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which de-allocates the memory so that it can be used for other purposes.

When you are allocating memory using malloc, make sure that that 0 (zero) bytes are not allocated. According to the documentation, behaviour for malloc() for this case is undefined. Always check for the pointer to the memory returned by calloc/malloc. If this pointer is NULL then the memory allocation should be considered unsuccessful and no operations should be performed using that pointer.

Recommended:   C Program to Sort an Array Using Selection Sort

free():

The library function free(void *ptr) de-allocates the memory previously allocated by a call to calloc, malloc, or realloc.

Share this:

Tags:

Kiran is a Software engineer by profession and Enthusiastic blogger, love to write articles on computer technology and programming. Reach him at kiran.troubleshootyourself@gmail.com.

1 Comment
  1. Excellent article. Keep writing such kind of info on your site.

    Im really impressed by your site.
    Hey there, You’ve performed a fantastic job.

    I’ll definitely digg it and personally suggest to my friends.
    I’m sure they will be benefited from this web site.

Leave a reply

Troubleshootyourself
Logo
Shopping cart