首页 > 解决方案 > 为什么这个程序返回 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;
}

标签: c++

解决方案


问题是您修改了指针sand t,这意味着它们不再指向 . 返回的相同位置new[]

当您使用时,delete[]您必须使用与返回的完全相同的指针new[]

不传递正确的指针会delete[]导致未定义的行为

作为一个简单的解决方案,使用其他临时变量代替sandt直接。作为一个合适的解决方案,使用std::string和迭代器。


推荐阅读