user637965
user637965

Reputation:

segmentation fault c++

I'm getting a segmentation fault and I have no idea how to debug it! It occurs after the creation of the MyString array i.e. the array created without any issue.

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;
        }
}

So I think it may be something in how I overloaded the + operator here:

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;
}

Any kind of help or advice would be appreciated!

Upvotes: 0

Views: 318

Answers (1)

Sanjay Manohar
Sanjay Manohar

Reputation: 7026

You attempt to delete str1.pString about half way through your + method.

but str1 is passed as a const MyString, which points to a static string in the program. You cannot deallocate this!

most likely this is the cause. You should not modify either str1 or str2 in your operator.

If I have understood your prog correctly, you want to modify the input string. To do this, you must construct your initial MyString with a real char[] character array, rather than a static quoted string like "outrageous".

so,

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 is now mutable;

Upvotes: 1

Related Questions