简体   繁体   中英

Why does my program crashes when I tried adding a node inside a function but works in the main function

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM