-1

I'm trying to write a simple version of the string class (for practice), and I have everything working except the overloaded + operator.

The line " strcpy_s(temp, strlen(stringPtr) + 1, stringPtr); " keeps throwing an exception. I assume strcat_s will too.

Any advice?

MyString MyString::operator+(const MyString & other)
{
    if (this != &other)
    {

        char * temp = new char[strlen(stringPtr) + strlen(other.stringPtr) + 1];
        strcpy_s(temp, strlen(stringPtr) + 1, stringPtr);
        strcat_s(temp, strlen(other.stringPtr) + 1, other.stringPtr);

        delete[]stringPtr;
        stringPtr = temp;

        delete[]temp;

    }
    return this->stringPtr;
}

If it helps, stringPtr is being passed "bob," and other.stringPtr is being passed "sally."

Lee
  • 15
  • 4

1 Answers1

1

You should pass the same size to both functions.

MyString MyString::operator+(const MyString & other)
{
    size_t newSize = strlen(stringPtr) + strlen(other.stringPtr) + 1;
    char * temp = new char[newSize];
    temp[0] = 0;
    strcpy_s(temp, newSize, stringPtr);
    strcat_s(temp, newSize, other.stringPtr);

    //I'm assuming your constructor makes a copy.....    
    MyString ret(temp);
    delete[] temp;
    return ret;
}

You might look at this for more info on a better way to implement some operators. E.g., operator+ is often implemented in terms of operator+=.

Phil M
  • 1,619
  • 1
  • 8
  • 10
  • Note, however, that you **know** that the allocated array is large enough for the concatenated strings, so the "secure" checks are redundant. `strcpy` and `strcat` are just as "safe" here. – Pete Becker Mar 02 '19 at 13:36