When and why to use malloc?

malloc is used for dynamic memory allocation. As said, it is dynamic allocation which means you allocate the memory at run time. For example when you don’t know the amount of memory during compile time.

One example should clear this. Say you know there will be maximum 20 students. So you can create an array with static 20 elements. Your array will be able to hold maximum 20 students. But what if you don’t know the number of students? Say the first input is the number of students. It could be 10, 20, 50 or whatever else. Now you will take input n = the number of students at run time and allocate that much memory dynamically using malloc.

This is just one example. There are many situations like this where dynamic allocation is needed.

Have a look at the man page malloc(3).

Leave a Comment