c - 当我尝试在函数中添加节点但在主函数中工作时,为什么我的程序崩溃了

标签 c pointers linked-list

我尝试使用以下方法为链表分配一个新节点:

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

当我尝试在调用 newnode() 的函数中执行此操作时,它崩溃了。但是,当它在main()函数内部完成时,它就起作用了。我的完整代码如下:

#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;
}

为什么会这样?

最佳答案

在你的 main() 函数中,

L->head->item=1;

L->head 未初始化。通过取消引用,您正在调用 undefined behavior .

在取消引用该指针之前,您需要为 L->head 分配内存。

关于c - 当我尝试在函数中添加节点但在主函数中工作时,为什么我的程序崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33691806/

相关文章:

C - 如何统计txt文件中的单词数?

c - gdb单步调试C程序

C 链表大小不受malloc限制

c - C中void函数的return语句

C - 从文件中读取字符串。获取随机字符

C++ 指针对象与非指针对象

c - 在 C 中预定义结构

c - 数组和指针不同

performance - OCaml 中的恒定时间列表串联

scala - 链表的用例