分割故障c++

segmentation fault c++

本文关键字:c++ 故障 分割      更新时间:2023-10-16

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

void ConcatTest()
{
    cout << "n----- Testing concatentation on MyStringsn";
    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;
}

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

您在+方法进行到一半的时候尝试delete str1.pString

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

很可能是这个原因。您不应该修改操作符中的str1str2

如果我正确理解了你的程序,你想修改输入字符串。要做到这一点,必须使用真实的 char[]字符数组来构造初始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

this string1现在是可变的;