Why would I use malloc when same job can be done by without malloc as below..
#include
#include
struct node {
int data;
In the first case, memory is allocated on the stack. When the variable n1
runs out of scope, the memory is released.
In the second case, memory is allocated on the heap. You have to explicitly release memory resources (as you are doing with free
).
Rule-of-thumb can be that you use stack-allocated memory for local, temporary data structures of limited size (the stack is only a portion of the computer's memory, differs per platform). Use the heap for data structures you want to persist or are large.
Googling for stack and heap will give you much more information.