【问题标题】:segmentation fault c++分段错误 C++
【发布时间】:2011-10-20 00:44:40
【问题描述】:

我遇到了分段错误,我不知道如何调试它!它发生在 MyString 数组创建之后,即创建的数组没有任何问题。

void ConcatTest()
{
    cout << "\n----- Testing concatentation on MyStrings\n";

    const MyString s[] =
            {MyString("outrageous"), MyString("milk"), MyString(""),
            MyString("cow"), MyString("bell")};

    for (int i = 0; i < 4; i++) {
            cout << s[i] << " + " << s[i+1] << " = " << s[i] + s[i+1] << endl;
        }
}

所以我认为这可能与我在这里重载 + 运算符的方式有关:

MyString operator+(MyString str1, MyString str2)
{
    MyString resultStr = MyString();
    delete [] resultStr.pString;
    resultStr.pString = new char[strlen(str1.pString) + strlen(str2.pString) + 1];
    MyString temp = MyString();
    delete [] temp.pString;
    temp.pString = new char[strlen(str1.pString) + 1];
    strcpy(temp.pString, str1.pString);
    delete [] str1.pString;
    str1.pString = new char[strlen(str1.pString) + strlen(str2.pString) + 1];
    strcpy(str1.pString, temp.pString);
    strcat(str1.pString, str2.pString);
    strcpy(resultStr.pString, str1.pString);
    return resultStr;
}

任何形式的帮助或建议将不胜感激!

【问题讨论】:

    标签: c++ segmentation-fault


    【解决方案1】:

    您尝试 delete str1.pString 大约在您的 + 方法的一半。

    但是str1 是作为const MyString 传递的,它指向程序中的一个静态字符串。 你不能释放这个!

    这很可能是原因。您不应修改运算符中的 str1str2

    如果我正确理解了你的编,你想修改输入字符串。为此,您必须使用 real char[] 字符数组而不是像“outrageous”这样的静态引号字符串来构造您的初始 MyString

    所以,

    char* ch1="outrageous";   // ch1 points to a nonmutable memory area
    char* str1 = new char[strlen(ch1)];  // str1 now points to a mutable region of memory
    strcpy(str1,ch1); // that mutable region now contains the static string
    
    MyString string1 = new MyString(str1); // this string is now writable/changeable
    

    这个string1 现在是可变的;

    【讨论】:

    • 是的,函数声明中的 str1 和 str2 可以使用“const”。
    猜你喜欢
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多