繁体   English   中英

分割错误c ++

[英]segmentation fault c++

我遇到了分段错误,我不知道如何调试它! 它在创建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;
}

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

您尝试通过+方法的一半delete str1.pString

但是str1作为const MyString传递,它指向程序中的静态字符串。 您无法取消分配!

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

如果我正确理解了您的编,则需要修改输入字符串。 为此,必须使用真实的 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是可变的;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM