c - C--Linked List中的段错误

标签 c linked-list segmentation-fault malloc

我知道当您尝试访问程序范围之外的内存时会发生设置错误,但我无法弄清楚我的错误发生在哪里,也不知道为什么。我定义了一个列表: *ListType list = NULL; , 然后我将数据添加到列表中,调用 main 中的添加函数: addNodeToList(&列表, 歌曲);

void addNodeToList(ListType **list, SongType *song)
{
    printf("Starting Add");

    NodeType *newNode = malloc(sizeof(NodeType));
    NodeType *currNode;
    currNode = (*list)->head;
    newNode->data = song;
    newNode->next = NULL;

    if(currNode == NULL) {
        printf("List is Empty");
        (*list)->tail = newNode;
        (*list)->head = newNode;
    }
    else {
        (*list)->tail->next = newNode;
        (*list)->tail = newNode;
    }

}

我传递的歌曲已正确初始化,我可以访问它的元素,所以我知道这不是导致段错误的原因。任何帮助将不胜感激!

typedef struct Song {
  char title[MAX_STR];
  char artist[MAX_STR];
  char album[MAX_STR];
  char duration[MAX_STR];
} SongType;

typedef struct Node {
  struct Node *next;
  SongType *data;
} NodeType;

typedef struct List {
  NodeType *head;
  NodeType *tail;
} ListType;

最佳答案

main 中声明

 ListType* list = NULL;

然后在你调用的函数中

 (*list)->head

取消引用 (*list) 很好,但是一旦您执行 ->head ,它就会尝试取消引用原始的 NULL 赋值。您需要先为 list 分配一些空间。

关于c - C--Linked List中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461379/

相关文章:

C - 神秘的线程段错误

c++ - 无法找出 C++ 代码的段错误

c - 系统函数调用时出现段错误

有人可以解释一下吗?它处理 C 中的 malloc 和全局数组

c - 查看 C 中的头文件

我的C套接字编程函数中connect不成功

c - C中struct的动态内存分配

c - 将新节点添加到我的链表堆栈中会将所有旧节点更新为新节点

c - C语言中向链表栈添加节点

c - 将指针传递给列表、函数