用栈(数组表示)实现括号匹配运行返回状态码-1073741510如何解决
括号匹配栈实现崩溃问题修复
代码错误点
- 栈结构体指针
st未分配内存就直接访问成员,属于野指针非法访问,是进程直接终止的核心原因。仅声明struct stack *st不会为结构体实例分配内存,需要先为结构体本身申请堆内存。 - 缺失
push、pop、isEmpty三个核心栈操作函数的实现,会触发未定义引用错误。 parenthematch函数语法不完整,缺少函数闭合括号,且遍历完字符串后没有判断栈是否为空(确认所有左括号都已匹配弹出),也没有设置对应返回值。- 未引入
<stdio.h>头文件,调用printf会编译报错。 - 动态申请的内存未手动释放,存在内存泄漏风险。
修复后完整可运行代码
#include <stdio.h> #include <stdlib.h> struct stack { int size; int top; char *arr; }; // 栈空判断函数 int isEmpty(struct stack *st) { return st->top == -1; } // 入栈函数 void push(struct stack *st, char c) { st->arr[++(st->top)] = c; } // 出栈函数 void pop(struct stack *st) { if (!isEmpty(st)) st->top--; } int parenthematch(char *pt) { // 先为栈结构体本身分配内存 struct stack *st = (struct stack *)malloc(sizeof(struct stack)); st->size = 100; st->top = -1; st->arr = (char *)malloc(st->size * sizeof(char)); for (int i = 0; pt[i] != '\0'; i++) { if (pt[i] == '(') { push(st, '('); } else if (pt[i] == ')') { if (isEmpty(st)) { // 提前返回前先释放内存避免泄漏 free(st->arr); free(st); return 0; } pop(st); } } int res = isEmpty(st); // 释放申请的内存 free(st->arr); free(st); return res; } int main() { char *p = "(34)(4(5+6))"; if (parenthematch(p)) { printf("parenthesis match \n"); } else { printf("Not match"); } return 0; }
内容的提问来源于stack exchange,提问作者Soham
相关产品推荐
相关产品推荐

