使用GDB调试时分段错误消失

问题描述 投票:0回答:1

我在运行此代码时遇到分段错误

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;

class cipher {
    public:
        char letter;
        int frequency;
};

bool comp(const cipher &A, const cipher &B) {
    if(A.frequency<B.frequency)
        return true;
    else
        return false;
}

vector<cipher> cipherF;

int posOf(char c)
{
    int i;
    for(i=0; i<26; ++i)
        if(cipherF[i].letter == c)
            return i;
    return -1;
}

int main()
{
    int t;
    cin >> t;
    string tmp;
    getline(cin, tmp);
    while(t--) {
        cipherF.clear();
        for(int i=97; i<=122; ++i)
        {
            cipher cip;
            cip.letter = i;
            cip.frequency = 0;
            cipherF.push_back(cip);
        }

        string txtF, cipherText;
        getline(cin, txtF);
        getline(cin, cipherText);

        for(int i=0; i<cipherText.size(); ++i)
        {
            char c = tolower(cipherText[i]);
            ++(cipherF[c-97].frequency);
        }

        stable_sort(cipherF.begin(), cipherF.end(), comp);
        for(int i=0; i<cipherText.size(); ++i)
        {
            int pos = posOf(cipherText[i]);
            if(pos == -1)
                continue;
            else if(isupper(cipherText[i]))
                cipherText[i] = toupper(txtF[pos]);
            else
                cipherText[i] = txtF[pos];
        }
        cout << cipherText << endl;
    }
}

问题是当我在 GDB 中运行它时,代码运行得很好并且非常出色。为什么它在 GDB 中运行没有任何分段错误,但在其他所有地方运行却出现分段错误?

这是我试图解决的问题:http://www.codechef.com/DEC13/problems/CHODE

c++ gdb segmentation-fault
1个回答
3
投票

问题是您的输入包含不在

[a-Z]
范围内的字符。例如:
!
这会导致在无效索引处访问向量。

您可以使用

valgrind
检查运行程序的这些内容。

valgrind ./ideone < stdin
...
==2830== Invalid read of size 4
==2830==    at 0x40111A: main (ideone.cpp:53)
...
==2830== Invalid write of size 4
==2830==    at 0x401120: main (ideone.cpp:53)

问题出在这几行:

    for(int i=0;i<cipherText.size();++i)
    {
        char c = tolower(cipherText[i]);
        ++(cipherF[c-97].frequency);
    }

c - 97
可能低于0。

您可以检查,例如:

    for(int i=0;i<cipherText.size();++i)
    {
        char c = tolower(cipherText[i]);
        if (c < 'a' || c > 'z') continue;
        ++(cipherF[c-97].frequency);
    }
© www.soinside.com 2019 - 2024. All rights reserved.