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;
?
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. C passes by value instead of reference.
Malloc() VS Calloc(): Explore the Difference between malloc() and 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.
Memory allocation (malloc), is an in-built function in C. This function is used to assign a specified amount of memory for an array to be created. It also returns a pointer to the space allocated in memory using this function.
Use malloc() if you are going to set everything that you use in the allocated space. Use calloc() if you're going to leave parts of the data uninitialized - and it would be beneficial to have the unset parts zeroed. 3.
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).
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