Function returns the oldest value in linked list

Viewed 80

This is a function (last) that returns the oldest value in linked list (the last node):

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

typedef struct node {
  int val;
  struct node *next;
}Elem, *Pointer;

Pointer init() { return NULL; }

void last(Pointer l)
{
  while (l != NULL)
  {
    l = l->next; 
  }
  printf("%d",l->val); 
}

int main(void) {
    Pointer myl =
    insert(3, insert(7, insert(5, 
    insert(11, insert(1, init ())))));

    last(myl);
}

so the function (last) takes a pointer that points to a linked list, and in a while loop it moves the pointer to the last node and then prints its value.

Error is: exited, segmentation fault.

2 Answers

Since checking for NULL l is your exit condition from the loop, when you reach the end of the loop

while (l != NULL)
{
    l = l->next; 
}
printf("%d",l->val); 

l is NULL (otherwise you would still be looping!). So in the following printf you are dereferencing a NULL pointer and this results in a segmentation fault.

You can modify your function in the following way:

void last(Pointer l)
{
    if ( l != NULL )
    {
        while (l->next != NULL)
        {
            l = l->next; 
        }
        printf("%d",l->val); 
    }
}

Just peek in the next field of the element, after making sure that the list is not empty (NULL list pointer).

  1. Never hide pointers behind the typedefs. It makes programs hard to read and error prone.
typedef struct node {
  int val;
  struct node *next;
}Elem;
  1. This is something absilutelly horrible - avoid
insert(3, insert(7, insert(5, 
insert(11, insert(1, init ())))));
  1. The function. Check if the next value is NULL. IMO better return pointer and then do something with it. Also Always check if parameter is valid.
Elem *last(Elem *first)
{
    if(first)
    {
        while(first -> next != NULL) 
        {
            first = -first -> next;
        }
    }
    return first;
}
  1. Print it
printf("%d\n", last(myl) -> val);
Related