c - 为什么会出现段错误?

标签 c pointers struct linked-list segmentation-fault

出现段错误的原因有哪些? 在下面的代码中,我尝试创建一种使用链接列表的简单方法。 基本上在我的程序中,您只需使用 linkedList 结构类型创建一个列表。 然而,程序中有一行导致了段错误。为什么会出现这种情况? 任何帮助将非常感激。谢谢:)

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

struct node{
    int num;
    struct node *next;
};
//Make the struct

typedef struct {
    struct node * first;
    struct node * current;
}linkedList;

void addNode(linkedList list, int a);
void addFirstNode(linkedList list, int b);
//Function prototypes

int main() {

    linkedList list;
    addFirstNode(list, 1);
    addNode(list, 2);
    addNode(list, 3);
    addNode(list, 4);
    addNode(list, 5);
    addNode(list, 6);
    addNode(list, 7);
}

void addFirstNode(linkedList list, int input) { 

    list.first = (struct node *)malloc(sizeof(struct node));   //Make first node
    list.first -> num = input;                                 //Fill first node
    list.current = list.first;                                     
}
void addNode(linkedList list, int input) {

   struct node * newNode = (struct node *)malloc(sizeof(struct node)); 
   newNode -> num = input;                      
   list.current -> next = newNode;    //Segmentation fault! (core dumped)
   list.current = newNode;
}

最佳答案

正如评论中所指出的,您的代码中有很多地方需要纠正:

  • 您需要通过引用传递函数参数(C 通过值传递元素)。
  • 您需要初始化链接列表,否则您将尝试取消引用 NULL 指针。

这是代码的正确版本:

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

struct node{
    int num;
    struct node *next;
};
//Make the struct

typedef struct {
    struct node * first;
    struct node * current;
}linkedList;

void addNode(linkedList* list, int a);
void addFirstNode(linkedList* list, int b);
//Function prototypes

int main() {

    linkedList *list = (struct node *)malloc(sizeof(struct node));;
    addFirstNode(list, 1);
    addNode(list, 2);
    addNode(list, 3);
    addNode(list, 4);
    addNode(list, 5);
    addNode(list, 6);
    addNode(list, 7);
}

void addFirstNode(linkedList* list, int input) {

    list->first = (struct node *)malloc(sizeof(struct node));   //Make first node
    list->first->num = input;                                 //Fill first node
    list->current = list->first;
}
void addNode(linkedList *list, int input) {

    struct node * newNode = (struct node *)malloc(sizeof(struct node));
    newNode->num = input;
    list->current->next = newNode;    //Segmentation fault! (core dumped)
    list->current = newNode;
}

关于c - 为什么会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45293064/

相关文章:

c++ - 将 C++ 结构填充为 2 的幂

为算术转换指针 - C

c++ - 结构填充

c - 如果 snprintf 在格式说明符中间停止,如何继续?

c - Opengl ES 2.0 中的 glFrustrum 变体 - 如何修复黑屏?

c - 用指针编译c代码时出现段错误

pointers - Go 语言中地址的按位异或

c++ - 使用 malloc 在 C++ 中动态分配结构

CMake 抑制项目的语言支持(与第 3 方库链接)

c - '&' 操作后存储的值是多少