【问题标题】:Segmentation fault when appending to a linked list附加到链表时出现分段错误
【发布时间】:2019-10-28 17:55:16
【问题描述】:

我正在尝试创建一个链接列表,但到目前为止我一直遇到分段错误。

通过一些测试,我已经设法找出它发生的位置,但我不确定它为什么会发生。

在线触发:tempo->fileName = str;
是因为我试图对指针进行分配还是我不知道的其他原因?

typedef struct listnode{
  struct listnode* next;
  char* fileName;
} listnode;

struct listnode* head;

//This section of code will be dedicated to the creation and management
//of the listnode functions

listnode* createNode(char* str, listnode* next){
  listnode* tempo;
  tempo = (listnode*)malloc(sizeof(struct listnode));

  if(tempo = NULL){
    printf("Error creating space for new node.\n");
    exit(0);
  }

  tempo->fileName = str;
  tempo->next = next;

  return tempo;
}

【问题讨论】:

  • ??????小心前行,看看会发生什么?
  • 提示:tempo = NULL 是做什么的?
  • 这就是为什么你应该在编译时使用-Wall -Wextra

标签: c linked-list segmentation-fault


【解决方案1】:

条件if(tempo = NULL) 中有错误。您分配的是tempo = NULL,而不是比较tempo == NULL。然后你做tempo->fileName = str,它实际上是在访问一个NULL 指针。仅仅因为您正在编写条件它不会使 = 运算符成为相等运算符,它仍然是一个赋值运算符。比较运算符是==

将条件改为:

if(tempo == NULL)

【讨论】:

    最近更新 更多