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.

free():

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

Check and run the program here:

You can run the above program on codeboard editor and see the results. You are allowed to modify code and run. In the editor there is a menu at the top-right corner. Here you can see two buttons such as ‘Compile’ and ‘Run’.

Share this:

Tags:

We will be happy to hear your thoughts

Leave a reply