1

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
ghost
  • 33
  • 6
  • 1
    You are passing a *copy* of the pointer. When that is modified in the function, the change is not reflected in the calling module. You need to pass a **pointer to a pointer**. ... Looking for a suitable duplicate question... – Adrian Mole Oct 14 '20 at 16:27
  • The `head` parameter of the `insert_beg` function behaves like a local variable. – Ian Abbott Oct 14 '20 at 16:28
  • Possible dup: [Updating pointers in a function](https://stackoverflow.com/questions/29658614/updating-pointers-in-a-function) – Weather Vane Oct 14 '20 at 16:31

1 Answers1

2

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" );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335