c++ - 奇怪的段错误

标签 c++

我一直在做的是一个反向波兰符号计算器。我在编译下面的程序时遇到了这个错误:

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);
                }
             }
 };

然后在我的主要功能中:

 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--;
  }
  }
  ...

我已经非常仔细地检查了任何可能的内存插槽非法分配或调用以及所有。没有线索...

PLUS:p 在这种情况下不会溢出。

最佳答案

int p=9,i;//p refers to the top of the stack

...

b->binary(stack[p+1],stack[p+2],s);
stack[p+1]=NULL;
stack[p+2]=b;

好吧,超限了。 stack[p+1]stack[10]stack[p+2]stack[11] 在你的十元素数组中。你正在写越过数组的边界(除非 ... 包含正确调整 p 的代码,但我无法知道)。

解决该问题后,您需要初始化堆栈 数组。当前,您有一个包含 10 个指向 Expression 的指针的数组。它们都没有被初始化为指向任何有效的东西,你稍后可以取消引用它们。

还有...

b->binary(...)

不会编译。

关于c++ - 奇怪的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8173008/

相关文章:

c# - C++ 到 C# 桥接多个进程

c++ - malloc什么时候不调用mmap?

c++ - 在 std::set 中查找 std::vector 的元素

c++ - 如何在 C++ 中将 int 转换为枚举?

c++ - 派生类中的私有(private)重写虚函数

c++ - openMP 练习 omp_bug2.c

c++ - 枚举的元编程问题

Visual Studio 2012 : LPCWSTR and wstring 中的 C++ 编译错误

c++ - 获取 std::future 的状态

c++ - C++ 中带有纯虚方法的抽象模板类