When and why to use malloc?

pr1m3x picture pr1m3x · Jan 10, 2012 · Viewed 63.3k times · Source

Well, I can't understand when and why it is needed to allocate memory using malloc.

Here is my code :

#include <stdlib.h>

int main(int argc, const char *argv[]) {

  typedef struct {
    char *name;
    char *sex;
    int age;
  } student;


  //Now I can do two things
  student p;

  //or
  student *ptr = (student *)malloc(sizeof(student));

  return 0;
}

Why is it needed to allocate memory when I can just use student p;?

Answer

taskinoor picture taskinoor · Jan 10, 2012

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).