c++ - 为什么这个程序返回 free() 无效指针?
问题描述
为什么这个程序会返回诸如 free() 无效指针之类的错误.....我尝试在纸上解决相同的输入 4$2*3-3+8/4/(1+1) 它应该可以工作。谁能帮我解决这个问题?我已经浪费了 2 小时以上的时间来查看这个程序。我尝试评论一些陈述,发现 conver 功能无法正常工作。
#include<iostream>
#include<string.h>
using namespace std;
const int MAX=50;
class infix{
private:
char Stack[MAX];
char *s,*t;
int top;
public:
infix();
~infix();
void setexpr(char *s);
void push(char c);
char pop();
void convert();
int priority(char c);
void show();
};
////////////////////////////////
infix::infix(){
top=-1;
}
////////////////////////////////
infix::~infix(){
delete[] s;
delete[] t;
}
////////////////////////////////
void infix::setexpr(char *str){
s=new char[strlen(str)+1];
t=new char[strlen(str)+1];
strcpy(s,str);
//cout<<s;
}
////////////////////////////////
void infix::push(char c){
if(top==MAX-1)
cout<<"Stack if full.";
else
Stack[++top]=c;
}
////////////////////////////////
char infix::pop(){
if(top==-1){
cout<<"Stackk is empty";
return -1;
}
else
return Stack[top--];
}
////////////////////////////////
void infix::convert(){
while(*s){
if(*s==' ' || *s=='\t'){
s++;
continue;
}
if(isdigit(*s) || isalpha(*s)){
while(isdigit(*s) || isalpha(*s)){
*t=*s;
s++;
t++;
}
}
if(*s=='('){
push(*s);
s++;
}
char opr;
if(*s=='*' ||*s=='+' ||*s=='/' ||*s=='%' ||*s=='-' ||*s=='$'){
int flag=1;
if(top!=-1){
opr=pop();
while(priority(opr)>=priority(*s)){
*t=opr;
t++;
if(top!=-1)
opr=pop();
else{
break;
flag=0;
}
}
if(flag)
push(opr);
push(*s);
}
else
push(*s);
s++;
}
if(*s==')'){
opr=pop();
while((opr)!='('){
*t=opr;
t++;
opr=pop();
}
s++;
}
}
while(top!=-1){
char opr=pop();
*t=opr;
t++;
}
*t='\0';
}
////////////////////////////////
int infix::priority(char c){
if(c=='$')
return 3;
if(c=='*' || c=='/'||c=='%')
return 2;
else{
if(c=='+' || c=='-')
return 1;
else
return 0;
}
}
////////////////////////////////
void infix::show(){
cout<<t<<endl;
}
////////////////////////////////
int main(){
char expr[MAX];
infix q;
cout<<"\nEnter an expression in infix form :";
cin.getline(expr,MAX,'\n');
q.setexpr(expr);
q.convert();
cout<<"\nThe postfix expression is :";
q.show();
return 0;
}
解决方案
问题是您修改了指针s
and t
,这意味着它们不再指向 . 返回的相同位置new[]
。
当您使用时,delete[]
您必须使用与返回的完全相同的指针new[]
。
不传递正确的指针会delete[]
导致未定义的行为。
作为一个简单的解决方案,使用其他临时变量代替s
andt
直接。作为一个合适的解决方案,使用std::string
和迭代器。
推荐阅读
- c# - 如何在字典键中添加占位符花括号
- html - 撇号在 windows、chrome 浏览器中显示为 ’
- c - C 编程使用 malloc 和赋值
- razor - 无法在 ASP.NET 核心 2.0 类项目中使用 TagHelper 在“cshtml”中添加条码
- dependencies - python的所有RDEPENDS是否需要在Yocto的IMAGE_INSTALL_append中显式定义?
- homebrew - 在 MacOS High Sierra 上通过 Homebrew 安装 Python 2 时出错
- java - 无法实例化 ExpandableListAdapter,因为它是抽象的
- python - Python 二维数组赋值
- android - 使用 Apk Easy 工具签名后 Apk 不起作用?
- automation - 如何禁用特定 SpecFlow 场景的并行运行?