我只收到某些编译器的Segfault

时间:2013-12-28 18:00:25

标签: c++ segmentation-fault

我编写了以下代码来加密文本(它远未完成):

#include <iostream>
#include <string>

using namespace std;

class Device {
    string input;
    string encrypted;
    string decrypted;
    string key;
    int keysize;

public:
    Device(string inp) {
        input = inp;
        keysize = 0;
    }

    int give_key(string ikey) {
        key = ikey;
        keysize = key.size();
    }

    string encrypt() {
        if(key != "") {
            for(int enc = 0, keyiter = 0; enc < input.size(); ++enc, ++keyiter) {
                cout << "Starting loop #" << enc << endl;
                if(keyiter == keysize) keyiter = 0; //Reset key iter

                int coffset = key[keyiter] - 48;
                cout << "Setting offset to " << coffset << endl;

                int oldspot = input[enc];
                cout << "Setting oldspot to " << oldspot << endl;

                cout << "Char " << input[enc] << " changed to ";
                //Skip non-letters between upper and lowercase letters
                if((input[enc] + coffset) > 90 && (input[enc] + coffset) < 97) {
                    int holder = 90 - oldspot;
                    input[enc] = (coffset - holder) + 97;

                }
                else if((input[enc] + coffset) > 122) {
                    int holder = 122 - oldspot;
                    input[enc] = (coffset - holder) + 65;
                }
                else {
                    input[enc] += coffset;
                }
                cout << input[enc] << endl;
                cout << endl;
            }
        }
        else {
            cout << "Key not set!" << endl;
        }

        cout << "Setting Encrypted" << endl;
        encrypted = input;

        cout << "Finishing encryption function" << endl;
    }

    string get_encrypt() {
        return encrypted;
    }

};


int main()
{
    Device device("AbCdEfG");
    device.give_key("12345");
    device.encrypt();
    cout << device.get_encrypt() << endl;

    cout << "Done" << endl;
    int wait; cin >> wait;
}

在C4Droid(Android IDE)上,显示“完成加密功能”后立即显示分段错误。 C4Droid没有调试器,所以我将它加载到我的PC上的Code :: Blocks并运行调试器,但它运行没有错误。我尝试了不同的输入和键组合,但总是运行良好。有谁知道问题可能是什么?我的问题完全是关于奇怪的段错误。

1 个答案:

答案 0 :(得分:6)

encrypt方法添加return语句。当前代码也为我抛出了一个分段错误,因为返回类型string是一个类,并且在执行encrypt之后,尝试破坏返回的对象,但返回值从未正确初始化。 / p>

还要注意所有警告:

../src/Test.cpp: In member function ‘int Device::give_key(std::string)’:
../src/Test.cpp:26:1: warning: no return statement in function returning non-void [-Wreturn-type]
../src/Test.cpp: In member function ‘std::string Device::encrypt()’:
../src/Test.cpp:30:49: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
../src/Test.cpp:63:1: warning: no return statement in function returning non-void [-Wreturn-type]
../src/Test.cpp: In member function ‘std::string Device::decrypt()’:
../src/Test.cpp:70:1: warning: no return statement in function returning non-void [-Wreturn-type]