What I have been doing is a reverse polish notation calculator.I have met this error when compiling my program below:
class Expression {
protected:
string exp;
int value;
public:
void getExp();//extract the exp from Expression
void setExp(string s);//store s in Expression
void setValue(int n);//store n in Expression
int evaluate();//extract the value from Expression
};
...
class binary : public Expression {
public:
void binaryyy(Expression *x1,Expression *x2,string op){
if(op=="+"){
setValue(x1->evaluate()+x2->evaluate());
string x;
x.append(x2->getExp());
x.append("+");
x.append(x1->getExp());
setExp(x);
}
else if(op=="-"){
setValue(x1->evaluate()-x2->evaluate());
string x;
x.append(x2->getExp());
x.append("-");
x.append(x1->getExp());
setExp(x);
}
}
};
then in my main function:
int main(){
...
Expression *stack[10];
int p=9,i;//p refers to one slot above the top element of the stack
for(i=0;i<10;i++) stack[i]=NULL;
...
string s_input;
getline(cin,s_input);
istringstream sss(s_input);
while(!sss.eof() && p>-2){
sss>>s;
if(s=="+" || s=="-")
binary *b = new binary;
b->binary(stack[p+1],stack[p+2],s);
stack[p+1]=NULL;
stack[p+2]=b;
p++;
}
else if(s.isNumber())//s.isNumber() might not exist.it means that s is number...
{
Expression *c=new Expression;
istringstream ss(s);
int temp;
ss>>temp;
c->setValue(temp);
stack[p]=c;
p--;
}
}
...
I have checked very carefully for any possible illegal allocation or call of memory slots and all.NO CLUE…
PLUS:p would not overrun in this case.
Well there is an overrun.
stack[p+1]isstack[10]andstack[p+2]isstack[11]in your ten element array. You’re writing past the bounds of your array (unless the...contains code which adjustspcorrectly, but I have no way to know).After that problem is fixed you need to initialize your
stackarray. Currently you have an array of 10 pointer toExpression. None of them are initialized to point to anything valid though, and you later dereference them.Also…
Won’t compile.