why do we use malloc() in creating linked list?
i mean what is the benefit of using malloc()?
the real purpose to use linked list is to have dynamic memory allocation in your program.so to allocate a node dynamically in a linked list we use malloc()
can’t we create without malloc()?
Have a look at this - C Dynamic Memory Allocation Using malloc(), calloc(), free() & realloc().
Other than these built in functions mentioned in the link, you don’t have any other technique for dynamic memory allocation.
allocate memory for node in run time means dynamically allocate memory by compiler. It returns the 1st address of location. If there is any value given negative in malloc then it returns NULL
Malloc allocate memory at run time, it create a new node of given structure of link-list… which has info part and link part…
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.
Without Dynamic memory allocation its not possible…
Memory Allocation
malloc is used to allocate memory