0

I tried allocating a new node for a linked list using:

struct node *n;
n=(struct node*)malloc(sizeof(struct node));

When I try to do this inside a function which I call newnode(), it crashes. However, when it works when it is done inside the main() function.My full code is as follows:

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

struct node{
int item;
struct node *next;
};

struct linkedlist{
    int size;
    struct node *head;
};

void split(struct linkedlist *LL,struct linkedlist *L_odd,
struct linkedlist *L_even);

void printlist(struct linkedlist *LL);

void generate();

void newnode(int i,struct linkedlist *LL);

int main(){
    struct linkedlist *L=(struct linkedlist*)malloc(sizeof(struct linkedlist));
    L->head->item=1;
    newnode(2,L);
    newnode(3,L);
    printlist(L);
 return 0;
}

void split(struct linkedlist *LL,struct linkedlist *L_odd,
struct linkedlist *L_even){
    bool odd=1;
    bool start=1;
    struct node *temp=malloc(sizeof(struct node));
    struct node *tempo=L_odd->head;
    struct node *tempe=L_even->head;
    temp=LL->head;
    while (temp->next != NULL){
        if(odd==1){
            if (start == 1 ){
                start=0;
            }
            else{
            tempe->next=temp->next;
            tempe=tempo->next;
            }
            tempo->item=temp->item;
            odd=0;
        }
        else if(odd==0){
            tempo->next=temp->next;
            tempo=tempo->next;
            L_even->head->item=temp->item;
            odd=1;
        }
        temp=temp->next;
    }
}

void printlist(struct linkedlist *LL){
    struct node *temp=LL->head;
    do{
        printf("%d ",temp->item);
        temp=temp->next;
    }while(temp!= NULL);
}

void generate(){

}

void newnode(int i,struct linkedlist *LL){
    struct node *n;
    n=(struct node*)malloc(sizeof(struct node)); //Program crashes here
        printf("%d",LL->head->item);
    //n->item=i;
    struct node *temp=LL->head;

    while (temp->next!=NULL){
        temp=temp->next;
    }
    //temp->next=n;
    //n->next=NULL;
}

Why is this so?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Lew Wei Hao
  • 763
  • 1
  • 13
  • 25

1 Answers1

3

In your main() function,

L->head->item=1;

L->head is uninitialized. By de-referencing, you're invoking undefined behavior.

You need to allocate memory to L->head before you de-reference that pointer.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Thanks! That fixed it! I have a question though. How do I know when I need to use malloc to allocate memory to a pointer first? For example,there are certain cases where it is not needed like, int *p=&number . – Lew Wei Hao Nov 13 '15 at 11:43
  • @LewWeiHao All the cases where the pointer is not initialized to any valid memory address. – Sourav Ghosh Nov 13 '15 at 11:43