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!
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.
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.
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.
You need to allocate the space. Use malloc before the strcpy . Save this answer.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With