what is malloc…why and how to use it in code?
malloc is a command used for dynamic memory allocation in C. a common syntax for its usage is:
the value before malloc (int *) specifies the pointer type as malloc by default returns a void pointer. this typecasts it to the required type.
the value after…(sizeof(int)) decides the size of the memory to be allocated. if you want to create an array of n elements use:
int *A = (int )malloc(nsizeof(int));
now A is an array of n ints and can be accessed in the usual A[i] format.
malloc can also be used to allocate char, float, double etc format elements.
For further details:
using malloc we can avoid segmentation error occuring in coding.
Well, I also had the same question when I first wrote linked list program.
malloc. It stands for memory allocation.
If we don’t use malloc, what actually happens is your compiler starts using any random memory space from your RAM. Since the program is not authorized to use that space, it is illegal. And returns Segmentation fault(Core Dumped)(in gcc).
Here comes, malloc. It allocates the required memory to the compiler at runtime to use and program works well.