C语言栈实现代码scanf读取%c输入异常及功能修复求助
代码存在的问题及修正方案
问题根因
scanf格式符配置错误:你使用的" %c "中,%c后的空格会强制scanf持续匹配后续所有空白字符,直到遇到非空白字符才结束读取。这就导致输入d后触发读取阻塞,循环计数异常,无法达到预期的执行次数。正确写法为仅在%c前加空格(用于跳过之前输入残留的换行、空格等空白符),后面不带空格,即" %c"。- 堆内存分配大小错误:
push函数中malloc(sizeof(struct node *))仅分配了指针大小的内存,远小于struct node结构体所需的内存空间,会触发内存越界,引发未定义行为。需要修改为malloc(sizeof(struct node))。 pop函数无空校验:当栈为空(head为NULL)时调用pop,直接访问head->next会触发空指针解引用,导致程序崩溃,需要补充空指针判断逻辑,同时可以补充出栈节点的内存释放逻辑,避免内存泄漏。
修正后完整代码
#include <stdio.h> #include <stdlib.h> struct node { int value; struct node *next; }; struct node *push(struct node *head, int x) { // 修正内存分配大小 struct node *v = (struct node *)malloc(sizeof(struct node)); v->next = head; v->value = x; return v; } struct node *pop(struct node *head) { // 补充空栈校验 if (head == NULL) { return NULL; } struct node *temp = head; head = head->next; free(temp); // 释放出栈节点内存,避免内存泄漏 return head; } void print(struct node *head) { if (head == NULL) { printf("NULL\n"); } else { while (head != NULL) { printf("%d", head->value); if (head->next != NULL) { printf(" "); } head = head->next; } printf("\n"); } } int main() { struct node *head = NULL; char c; int n; scanf("%d", &n); for (int i = 0; i < n; i++) { // 修正scanf格式符,去掉%c后的空格 scanf(" %c", &c); if (c == 'a') { int x; scanf("%d", &x); head = push(head, x); print(head); } else if (c == 'd') { head = pop(head); print(head); } } // 程序退出前释放剩余栈节点内存,避免内存泄漏 while (head != NULL) { struct node *temp = head; head = head->next; free(temp); } return 0; }
内容的提问来源于stack exchange,提问作者imk
相关产品推荐
相关产品推荐

