PAYATHON 2026

为什么这段 C 链表插入代码会发生段错误?

数据小陈

结论

段错误发生在 insertNode() 里。第一个 while 结束后,list 指向的是 last,不再是链表头。调用 insertNode(3, list, new_element) 时,函数先执行 emplacement -= 2,得到 1;随后 for 循环执行一次 l = l->next。这时 last->next 是 NULL,所以 l 变成 NULL。接着执行 n->next = l->next; 就会解引用空指针,引发 segfault。

代码执行路径

  • list 是 malloc 分配的节点,但 list->data 没有初始化,所以第一行 data : 0 不能当作有效输出。
  • 执行 list->next = head 后,第一个 while 以 list->next != NULL 为条件;循环结束时 list == last。
  • 进入 insertNode() 后,tmp = (struct Node*)malloc(...); 刚分配的内存马上被 tmp = l; 覆盖,造成内存泄漏。
  • tmp = l; 使 tmp 指向传入的 last。如果后面的 free(tmp) 被执行,就会释放 last;但 main() 之后还会 free(last),所以有重复释放或非法释放的风险。
  • 参数 l 是按值传递的指针。函数内让 l 指向别的节点,不会改变 main() 里的 list。

修复思路

  1. 遍历链表时不要改动头指针,用临时变量 cur。
  2. 插入函数不要为了临时节点调用 malloc,也不要 free 调用者传入的节点。
  3. 插入可能改变头节点时,用 struct Node **headRef,或让函数返回新的头指针。
  4. 每次 malloc 只对应一次 free。new_element 插入链表后不要再单独 free,统一释放整条链表即可。
  5. 访问 l->next 前先确认 l != NULL,同时明确 emplacement 是从 1 开始还是从 0 开始。

可运行修复示例

示例采用“1-based 位置插入”:insertNode(3, &head, new_element) 会得到 1 -> 2 -> 8 -> 3。

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

struct Node {
    int data;
    struct Node *next;
};

void insertNode(int emplacement, struct Node **headRef, struct Node *n) {
    if (headRef == NULL || n == NULL) return;

    if (emplacement <= 1 || *headRef == NULL) {
        n->next = *headRef;
        *headRef = n;
        return;
    }

    struct Node *prev = *headRef;
    int i = 1;
    while (prev->next != NULL && i < emplacement - 1) {
        prev = prev->next;
        i++;
    }

    n->next = prev->next;
    prev->next = n;
}

void printList(const struct Node *head) {
    const struct Node *cur = head;
    while (cur != NULL) {
        printf("data : %d\n", cur->data);
        cur = cur->next;
    }
}

void freeList(struct Node *head) {
    while (head != NULL) {
        struct Node *next = head->next;
        free(head);
        head = next;
    }
}

int main(void) {
    struct Node *head = malloc(sizeof *head);
    struct Node *element = malloc(sizeof *element);
    struct Node *last = malloc(sizeof *last);
    struct Node *new_element = malloc(sizeof *new_element);
    if (!head || !element || !last || !new_element) return 1;

    head->data = 1;
    head->next = element;

    element->data = 2;
    element->next = last;

    last->data = 3;
    last->next = NULL;

    new_element->data = 8;
    new_element->next = NULL;

    printList(head);
    insertNode(3, &head, new_element);
    printf("insertion\n");
    printList(head);

    freeList(head);
    return 0;
}

注意事项

  • 原代码里的 list 是额外 malloc 出来的节点,list->data 没有赋值,不应把它当成有效数据打印。
  • 如果要用哑元节点(dummy head),需要初始化 list->data,遍历时从 list->next 开始;不要把“哑元节点”和“链表头节点”的语义混在一起。
  • 插入位置参数要和循环条件对应。“在第 3 个位置前插入”和“在第 3 个节点后插入”是两种不同语义。
  • 释放链表后不要再释放已经插入其中的节点,否则会造成 double free。

备注:内容仅供参考。