【问题标题】:Why does creating a linked list in my code create a segmentation fault?为什么在我的代码中创建链表会产生分段错误?
【发布时间】:2021-02-18 07:50:42
【问题描述】:

我正在尝试在 C 上做一个练习。有两个数组,countlistcount 是一个初始填充为 0 的整数数组,而 list 是一个队列数组。我的代码应该采用由空格分隔的数字对,例如。 “1 2”。对于每一对数字,我必须将count数组中的2nd number-1位置加1,然后在list数组的1st number-1位置的队列头部放入一个包含第二个数字的节点.我的代码在下面,在收到第一对数字后会导致分段错误。删除第 24-30 行会删除错误,但我不明白是什么导致了这个错误。谁能指出它为什么会出现分段错误?

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

typedef struct node Node;
struct node {
  int succ;
  Node *next;
};

void set_initial_array(int count[], int n, Node *list[]);
void handle_input(char string[], int count[], Node *list[]);

void set_initial_array(int count[], int n, Node *list[]) {
  for (int i = 0; i < n; i++) {
    count[i] = 0;
    list[i] = NULL;
  }
}

void handle_input(char string[], int count[], Node *list[]) {
  int j = atoi(&string[0]), k = atoi(&string[2]);
  count[k - 1]++;
  if (list[j - 1] != NULL) { // Removing line 24-30 removes error
    Node head = {k, list[j - 1]};
    list[j - 1] = &head;
  } else {
    Node head = {k, NULL};
    list[j - 1] = &head;
  }
}

int main() {
  char string[4];
  int count[15];
  Node *list[15];
  set_initial_array(count, n, list); //fill count with 0 and list with NULL
  while (fgets(string, 4, stdin) != NULL && strcmp(string, "0 0") != 0) {
    handle_input(string, count, list);
  }
}

【问题讨论】:

  • 这怎么编译,main中没有变量n
  • 非静态局部变量在从声明它们的函数返回时将失效,并将指向它们的指针存储到在 returnig 后仍然存在的变量不是一个好主意。

标签: c linked-list segmentation-fault


【解决方案1】:

这里有问题:

Node head = {k, list[j - 1]};
list[j - 1] = &head;

head 是一个局部变量,一旦handle_input 函数返回,它就会离开作用域(或者简单地说:它会被销毁)。

list[j - 1] = &amp;head; 这一行中,您将该局部变量的地址存储在列表数组中,该数组实际上指向main 中提供的数组。

您需要通过分配内存以不同方式处理此问题:

Node *head = malloc(sizeof(*head));
head->succ = k;
head->next = list[j - 1]
list[j - 1] = head;

但可能还有其他问题,我没有检查。

不要忘记在 main 的某个时间点释放分配的内存。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 2016-02-08
    • 2017-12-04
    • 2015-05-10
    • 2021-07-10
    相关资源
    最近更新 更多