0

我的程序崩溃了,这对我来说似乎很好,当然我的程序另有说明,这让我感到困惑。

我目前正在处理的这个函数片段:

        for(int k = 0; k < dictionary[k].size(); k++)
        {
            //"i" represents the fragment's first character
            //while "k" represents the dictionary first character
            if(fragments[i][j] == dictionary[k][j]) {
                token++;
                cout << token << endl;
            }
        }

可能是问题所在。当我调试问题时,调试器会转到代码段的第一行:

    for(int k = 0; k < dictionary[k].size(); k++)

然后当我尝试进入下一个时崩溃。在调试器中,此窗口在我的代码块中打开:

Signal Received

Program Received Singal SIGEGV, segmentation fault. Do you want to view backtrace?

我点击是,这对我来说似乎是任意的。

有谁知道我做错了什么?

如果需要回溯(窗口显示调用堆栈),如果需要,我稍后会对其进行编辑

编辑:这是整个功能,我认为没有必要

void Language::compare()
{
    int para = getParameters(0); //eg. 3

    int valid = para;
    int token = 0;

    for(int i = 0; i < para; i++)
    {
        //If the string is creater than 2 characters
        if(fragments[i].length() > 1) {
            for(int j = 0; j < fragments[i].length(); j++)
            {
                //Checking if that character match in dictionary
                for(int k = 0; k < para; k++) //Changed and now works,
                {
                    //"i" represents the fragment's first character
                    //while "k" represents the dictionary first character
                    if(fragments[i][j] == dictionary[k][j]) { //But now this line crashes
                        token++;
                        cout << token << endl;
                    }
                }
                if(token == 0) {
                    break;
                }
            }
        }
        else {
        //...
        }
    }
}

字典和片段在类“语言”中声明,它们都是向量。

4

5 回答 5

10

我怀疑您打算在dictionary[k].size()那里用作循环控制的一部分,因为循环正在迭代k. 你是说dictionary.size()还是dictionary[i].size()可能?

于 2009-09-03T21:26:42.977 回答
7

这一行:

for(int k = 0; k < dictionary[k].size(); k++)

确实很可疑。你确定你不想循环到字典数组/集合的大小吗?

如果您发布它的定义dictionary可能会帮助我们提供一些具体的建议。

于 2009-09-03T21:26:22.930 回答
1

fragments[i][j] == dictionary[k][j]

dictionary[k].size()>j在尝试取消引用之前,您应该确保dictionary[k][j]

于 2009-09-03T22:54:48.130 回答
0

The other comments about the test in the for loop looking suspect are probably correct, but in addition if you're getting this segfault the first time you try to go into the loop then it's possible that you're working with a dictionary vector<> that has no entries.

In this case dictionary[0].size() has undefined behavior (which might well be a segfault).

于 2009-09-03T21:54:06.123 回答
0

进入循环时 j 的值是多少?

我同意其他人的观点:

for(int k = 0; k < 字典[k].size(); k++)

似乎是假的。就像是

for(int k = 0; k < 字典[m].size(); k++)

似乎更有意义。

于 2009-09-03T21:30:43.277 回答