9

Possible Duplicate:
When should I use malloc in C and when don't I?

Hi, I'm new to the C language and found the malloc function. When should I use it? In my job, some say you have to use malloc in this case but other say you don't need to use it in this case. So my question is: When should I use malloc ? It may be a stupid question for you, but for a programmer who is new to C, it's confusing!

Community
  • 1
  • 1
kevin
  • 13,559
  • 30
  • 79
  • 104

2 Answers2

13

With malloc() you can allocate memory "on-the-fly". This is useful if you don't know beforehand how much memory you need for something.

If you do know, you can make a static allocation like

int my_table[10]; // Allocates a table of ten ints.

If you however don't know how many ints you need to store, you would do

int *my_table;
// During execution you somehow find out the number and store to the "count" variable
my_table = (int*) malloc(sizeof(int)*count);
// Then you would use the table and after you don't need it anymore you say
free(my_table);
Makis
  • 12,468
  • 10
  • 62
  • 71
  • 7
    I know this is old, but out of curiosity couldn't you just do: int my_table[count]; ? If so then why use malloc for this example? – John Powers Jul 26 '14 at 06:18
  • @JohnPowers I know it is late but have a look at https://stackoverflow.com/a/51451640/2806163 if you are still interested :) – Daksh Shah Dec 30 '18 at 13:49
  • @JohnPowers the compiler will get upset as it wants to know the size at compile time, not at run time. – RhythmInk Feb 22 '21 at 02:45
9

one Primary usage is, when you are working on a list of items and size of the list is unknown to you.

sunmoon
  • 1,448
  • 1
  • 15
  • 27