请指出新手编写的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
相关产品推荐
相关产品推荐

