0

I'm getting a segmentation fault and I don't know where the problem is.

#include "stdio.h"
#include "stdlib.h"

struct node {
    int data;
    struct node *next;
    };
    struct node *head = NULL;
    struct node * curr;
    struct node * newNode;

void createList(){

    int data,n , i ;
    scanf("%d",&n);
    for (i = 0 ; i < n ;i++){
        scanf("%d",&data);
        curr = head;
        newNode = (struct node*)malloc(sizeof(struct node));
        newNode->data=data;
        newNode->next=NULL;
        if ( curr == NULL){
            head = newNode;
        }else
            while (curr->next != NULL){
                curr = curr->next;
            }
            curr->next = newNode;
    }

}

int main(int argc, char const *argv[])
{

    createList();
    return 0;
}

Can you please figure out where? The first iteration is good but when i = 1, there is an error.

ryanpattison
  • 6,151
  • 1
  • 21
  • 28
Selim Ajimi
  • 344
  • 6
  • 21

1 Answers1

5

Alignment is not enough to make a block of code in C ;-)

Need braces. Without which the statement curr->next = newNode; is outside the else block which is not what you want.

  if ( curr == NULL){
                head = newNode;
   }
   else {
                while (curr->next != NULL){
                    curr = curr->next;
                }
                curr->next = newNode;
   }
P.P
  • 117,907
  • 20
  • 175
  • 238