Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use malloc in C? [duplicate]

Tags:

c

malloc

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!

like image 346
kevin Avatar asked Mar 31 '11 09:03

kevin


People also ask

When should you use malloc in C?

Malloc is used for dynamic memory allocation and is useful when you don't know the amount of memory needed during compile time. Allocating memory allows objects to exist beyond the scope of the current block.

Is it better to use malloc () or calloc ()?

malloc() and calloc() functions are used for dynamic memory allocation in the C programming language. The main difference between the malloc() and calloc() is that calloc() always requires two arguments and malloc() requires only one.

Should I always use malloc?

As it turns out, you do not need to use malloc() in every case. malloc() will allocate memory on the heap when it is used, but there is nothing stopping you from defining an object on the stack and initializing a pointer to a struct with the address of your stack-allocated struct.

Do you need to malloc for Strcpy?

You need to allocate the space. Use malloc before the strcpy . Save this answer.


1 Answers

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);
like image 81
Makis Avatar answered Sep 19 '22 15:09

Makis