As soon as we are leaving the funtion insert_beg, the memory allocated to head pointer is lost and the head pointer again becomes NULL. Why is this behaviour although I am passing the pointer? Please guide me to how to retain the memory block which is allocated by malloc().
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void insert_beg(struct node *head, int data)
{
if(head==NULL)
{
struct node *tmp_node;
tmp_node = (struct node*)malloc(sizeof(struct node));
tmp_node->data = data;
tmp_node->next = NULL;
head = tmp_node;
}
else
{
struct node *tmp_node;
tmp_node = (struct node*)malloc(sizeof(struct node));
tmp_node->data = data;
tmp_node->next = head;
head = tmp_node;
}
}
void display(struct node *head)
{
if(head==NULL)
{
printf("UNDERFLOW");
}
else
{
struct node *tmp = head;
while(tmp!=NULL)
{
printf("%d ", tmp->data);
tmp = tmp->next;
}
}
}
int main()
{
struct node *head = NULL;
insert_beg(head,12);
display(head);
} ```
Expected output: 12
Observed output: UNDERFLOW
The function insert_beg
deals with a copy of the value of the passed to it pointer to the head node. The parameter struct node *head
is a local variable of the function that gets the copy of the value of the original pointer to the head node. So changes of the local variable do not influence on the original pointer used as an argument
You should pass the pointer to the head node by reference.
In C passing by reference means passing an object indirectly through a pointer to it.
The function can be declared and defined the following way.
int insert_beg( struct node **head, int data )
{
struct node *tmp_node = malloc( sizeof( struct node ) );
int success = tmp_node != NULL;
if ( success )
{
tmp_node->data = data;
tmp_node->next = *head;
*head = tmp_node;
}
return success;
}
And the function can be called like
insert_beg( &head, 12 );
or like
if ( !insert_beg( &head, 12 ) )
{
puts( "There is no enough memory" );
}