You need to enable JavaScript to run this app. 请指出新手编写的C语言链表初始化代码的运行错误
优惠活动
大模型
产品
解决方案
定价
更多

请指出新手编写的C语言链表初始化代码的运行错误

代码错误说明
  • 缺少必要头文件:malloc 函数定义在 <stdlib.h> 中,当前代码仅引入 <stdio.h>,调用未声明的 malloc 属于语法错误,C99及以上标准的编译器会直接拒绝编译,即使老旧编译器允许通过,运行也会产生未定义行为。
  • 核心运行错误:main 函数中定义的 struct linkedlist *s 是未初始化的野指针,你没有为 linkedlist 结构体本身分配内存就直接将它传入 init 函数,init 中对 p->head、p->count 的赋值属于对非法内存地址的写入操作,会直接触发段错误导致程序崩溃。
  • 非标准写法:main 函数的标准返回值类型为 int,void main 仅在部分老旧编译器中被兼容,不符合ISO C标准要求。
修正后可运行代码
#include <stdio.h>
#include <stdlib.h> // 补全内存分配函数所需头文件
#define SIZE 5

struct node
{ 
    int item;
    struct node *link;
};

struct linkedlist
{
    struct node *head;
    int count;
};

void init(struct linkedlist *p , int key)
{
    struct node *newnode;
    newnode = (struct node*)malloc(sizeof(struct node));
    // 增加内存分配失败校验,避免野指针操作
    if (newnode == NULL) {
        perror("节点内存分配失败");
        return;
    }
    newnode->link = NULL;
    newnode->item = key;
    p->head = newnode;
    p->count = 1;
}

// 修正main函数返回值类型为标准int
int main()
{   
    // 为链表结构体本身分配合法内存空间
    struct linkedlist *s = (struct linkedlist*)malloc(sizeof(struct linkedlist));
    if (s == NULL) {
        perror("链表结构体内存分配失败");
        return 1;
    }
    init(s, 2);
    printf("%d", s->count);
    
    // 释放堆内存,避免内存泄漏
    free(s->head);
    free(s);
    return 0;
}

内容的提问来源于stack exchange,提问作者Ishraan Saha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 18:27:04