返回整数的分段错误

时间:2014-03-11 03:58:08

标签: c++ segmentation-fault

以下是我的结构:

struct LR_State{
    int myState;
    int operation;  //-1 initial.  0 if shift, 1 if reduce.
    vector<string> symbols;
    vector<int> indeces;

    LR_State(int myState){
        operation = -1;
        this->myState = myState;
    }

    void addTransition(int op, int index, string symbol){
        if (operation==-1){
            operation = op;
        }
        symbols.push_back(symbol);
        indeces.push_back(index);
    }

    int getIndexOfSymbol(string symbol){
        int index = -1;
        for (int i=0; i<symbols.size(); i++){
            if (symbols.at(i).compare(symbol)==0){
                index = indeces.at(i);
                break;
            }
        }
        return index;
    }

};

我遇到的问题是使用getIndexOfSymbol函数。它接受一个字符串,将其与符号向量中的元素匹配,然后在indeces向量中返回相应的索引。

以下是我的代码片段,是实际调用该函数的地方。 “states”是LR_States的向量。 getIndexSymbol的函数调用在shift部分没有任何问题,但是在reduce部分中出现。我试过调用确切的函数,导致segfault字面上在if语句之外,它不会导致段错误。只有在“其他如果...”内部才会发生段错误。

        cout << states.at(currState).getIndexOfSymbol(symbol) << endl;  //no segfault

        if (states[currState].operation==0){
            //shift
            int newState = states.at(currState).getIndexOfSymbol(symbol);  //no segfault
            stateStack.push_back(newState);
            symbolStack.push_back(symbol);
            iss >> symbol;

        }
        else if (states[currState].operation==1){

            //reduce
            int rule = states.at(currState).getIndexOfSymbol(symbol);  //segfault here!
            for (int i=0; i<rules[rule-1].size()-1; i++){
                stateStack.pop_back();
                symbolStack.pop_back();
            }
            symbolStack.push_back(rules[rule-1][0]);
            //get the new state
            int newState = states.at(currState).getIndexOfSymbol(rules[rule-1][0]);
            stateStack.push_back(newState);
            symbolStack.push_back(rules[rule-1][0]);

            for (int i=0; i<rules[rule-1].size(); i++)
                cout << rules[rule-1][i] << " ";
            cout << endl;
        }

我完全被这种不一致的段错误行为所困扰。

0 个答案:

没有答案