Nimbostratus
Nimbostratus

Reputation: 43

Why does the code below give a segmentation fault?

#include <stdio.h>
#include <stdlib.h>
struct node{
    int data;
    struct node *next;
 };

void print (struct node* ptr)
{
    struct node* iter = ptr;
    while (iter!=NULL)
    {
    printf ("%d",iter->data);
    iter = iter -> next;
    }
}

void printWantedIndice (struct node*ptr,int indice)
{
    struct node*iter=ptr;
    int counter=1;
    while (counter<indice)
    {
        iter = iter -> next;
        counter++;
    }
    printf ("%d",iter->next->data);
}

int main ()
{
    struct node* head = (struct node*)malloc(sizeof(struct node));
    head -> data = 15;
    head -> next -> data = 44;
    head -> next -> next  = NULL;
    print(head);

}

i tried to code linked list, first "print" function is for printing every indice, the second function "printWantedIndice" is a function for printing the wanted Indice .it gives a segmentation fault. i couldn't understand why. can you help with that?

Upvotes: 0

Views: 34

Answers (1)

Saucy Goat
Saucy Goat

Reputation: 1675

The following line is the cause:

head->next->data = 44;

Since head->next is not initialized, you'll get a segmentation fault from trying to access it.

Upvotes: 1

Related Questions