You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言链表实现多项式加法时出现Segmentation fault问题排查

多项式加法链表实现中的段错误问题分析与修复

核心错误点

  • 值传递无法修改外部指针
    createList函数的参数struct node* head是值传递,函数内部对head的赋值仅修改局部变量,不会影响外部的poly1。poly1是未初始化的全局野指针,后续访问poly1->coeff必然触发段错误。
  • 节点内存未重复分配
    createList中仅调用一次createNode()创建newNode,循环中反复复用同一节点的内存空间,既造成链表逻辑错误,也会引发后续内存访问问题。
  • 全局变量声明错误
    struct node* poly1,poly2,poly3;中,poly2和poly3是struct node实例而非指针,后续使用会出现类型不匹配问题(当前段错误主要关联poly1)。

测试场景差异解释

  • 场景1:循环执行两次,函数内部局部head指向节点,但外部poly1仍为野指针。退出循环后执行printf("%d",poly1->coeff),访问野指针指向的内存触发段错误。
  • 场景2:循环仅执行一次后退出,外部poly1依旧是未初始化的野指针,执行printf("%d",poly1->coeff)直接触发段错误。

修复后的代码

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

struct node{
    struct node* next;
    int coeff, power;
};

struct node* createNode(){
    struct node *temp = (struct node*)malloc(sizeof(struct node));
    temp->next = NULL;
    return temp;
}

// 修正全局变量声明,统一为指针类型并初始化为NULL
struct node* poly1 = NULL, *poly2 = NULL, *poly3 = NULL;

// 改用指针的指针传递,实现对外部指针的修改
void createList(struct node** head){
    int ch = 0;
    struct node* temp = NULL;

    while(ch != -1){
        struct node* newNode = createNode(); // 每次循环创建新节点
        printf("Enter coefficient and power: ");
        scanf("%d%d", &newNode->coeff, &newNode->power);

        if(*head == NULL){
            *head = newNode;
            temp = newNode;
        }else{
            temp->next = newNode;
            temp = newNode;
        }

        printf("Enter -1 to exit, other number to continue: ");
        scanf("%d", &ch);
    }
}

void display(struct node* head){
    struct node *temp = head;
    if(temp == NULL){
        printf("Linked List not present\n");
        return;
    }
    while(temp != NULL){
        printf("%dx^%d ", temp->coeff, temp->power);
        temp = temp->next;
    }
    printf("\n");
}

// 标准main函数返回int类型
int main(){
    printf("Enter the data for the first polynomial\n");
    createList(&poly1); // 传递poly1的地址
    display(poly1);
    return 0;
}

修复说明

  1. 参数传递改为指针的指针:通过struct node** head让函数内部能修改外部指针的指向,将创建的链表头赋值给poly1。
  2. 循环内创建新节点:每次循环调用createNode(),确保每个链表节点拥有独立内存空间。
  3. 修正全局变量声明:统一为指针类型并初始化为NULL,避免野指针问题。
  4. 标准化main函数:改为返回int类型,符合C语言标准规范。

内容的提问来源于stack exchange,提问作者Aman Nambisan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 06:50:50