为什么在我的代码中创建链表会产生分段错误?

Why does creating a linked list in my code create a segmentation fault?

我想做一个关于 C 的练习。有两个数组,countlistcount 是一个初始填充为 0 的整数数组,而 list 是一个队列数组。我的代码应该采用由 space 分隔的数字对,例如。 “1 2”。对于每一对数字,我必须在 count 数组中的 2nd number-1 位置加 1,然后在 1st number-1 位置的队列头部放置一个包含第 2 个数字的节点list 数组。我的代码在下面,它在收到第一对数字后导致分段错误。删除第 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);
  }
}

这里有问题:

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

head 是一个局部变量,一旦 handle_input 函数 returns.

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

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

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

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

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