1

I was completing a Hackerrank challenge involving addition of elements to a linked list and printing it.

The input is of this format: A set of integers, in which the first element gives the size and the rest are the components of the list.

I completed the challenge in Java, but I am not able to do it in C. Input of 4 2 3 4 1 should print 2 3 4 1, but this snippet that I coded is giving me 1 1 1 1 1 1 .... {truncated}

My approach: Declare a new struct temp of type Node (with the data input as data field, and NULL in next field), then iterate thorough the linked list with head as the starting point, and when it reaches the last element, change the next field of the last element to the address of the current element.

Code:

 #include <stdlib.h>
 #include <stdio.h> 

   typedef struct Node{
   int data;
   struct Node* next;
    }Node;

 Node* insert(Node *head,int data)
  {       
    Node temp = {data, NULL} ;

     if (head == NULL)
      { head =&temp;
        return head;
      }

     else{

    Node* current = head ;
    while(current->next !=NULL)
      current = current->next ;

      current->next = &temp;

      return head;
       }
   }

void display(Node *head)
{
Node *start=head;
while(start)
{
    printf("%d ",start->data);
    start=start->next;
}
}

int main()
{
int T,data;
scanf("%d",&T);
Node *head=NULL;    
while(T-->0){
    scanf("%d",&data);
    head=insert(head,data);
            }

 display(head);

 }
Ambareesh S J
  • 97
  • 1
  • 9

2 Answers2

5

List nodes must be allocated dynamically. This

Node temp = {data, NULL} ;

declares a local variable. Referring to its address outside the scope of its declaring function is undefined behavior.

Replace with

Node *temp = malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;

Now thtat temp is a pointer, expression &temp has to be replaced with temp as well.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • " Referring to its address outside the scope of its declaring function is undefined behavior " So here where does the scope of the declaring function end? When insert returns, there is no definite address value for temp? – Ambareesh S J Jan 25 '17 at 11:03
  • 1
    @AmbareeshSJ Correct, once `insert` function returns, the memory that was previously used by `temp` is up for re-use by other parts of your program, including `temp` inside another invocation of `insert`. Essentially, all nodes that you collected in your list are stored at the same invalid address. – Sergey Kalinichenko Jan 25 '17 at 11:12
2

Because you save a pointer to a local variable in the list. When the insert function returns, the local variable temp will go out of scope and cease to exist. Saving a pointer to it and using that pointer will lead to undefined behavior. Find a good beginners book and read about dynamic allocation of memory.

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621