Question

I have to create an overloaded String class for a homework assignment. I have ran into a problem while testing some operators:

int main() {
    MyString i;
    cin >> i;
    cin.ignore(100, '\n');
    MyString temp = i;
    while(!(i > temp)) {
        temp += i;
        cin >> i;
        cin.ignore(100, '\n');
    }
    cout << endl << temp;
    return 0;
}

MyString operator+= (const MyString& op1) {
    _len += (op1._len);
    char* temp = new char[_len+1];
    strcpy(temp, _str);
    strcat(temp, op1._str);
    if(_str) {
        delete [] _str;
        _str = NULL;
    }
    _str = new char(_len+1);
    strcpy(_str, temp);
    return *this;
}

istream& operator>> (istream& inStream, MyString& in) {
    char temp[TSIZE];
    inStream >> temp;
    in._len = strlen(temp);
    if(in._str) {
        delete [] in._str;
        in._str = NULL;
    }
    in._str = new char[in._len+1];
    strcpy(in._str, temp);
    return inStream;
}

MyString(const MyString& from) {
        _len = from._len;
        if(from._str) {
            _str = new char[_len+1];
            strcpy(_str, from._str);
        } else _str = NULL;
    }

explicit MyString(const char* from) {
    if(from) {
        _len = strlen(from);
    _str = new char[_len+1];
        strcpy(_str, from);
    } else {
        _len = 0;
        _str = NULL;
    }
}

I am still very new to this, but apparently the problem occurs the second time the += operator is called, not the first though. I am sorry if I did not give all the information needed, I did not want to include more than needed. Thank you for any help

Was it helpful?

Solution

_str = new char(_len+1);

By using parenthesis instead of square brackets there, you are allocating a single char and initializing it with a strange value. I'm pretty sure you meant to allocate an array.

_str = new char[_len+1];

But since you already allocated temp, why not just use that?

_str = temp;
// strcpy(_str, temp); // delete this line

This fixes your memory leak too. You weren't freeing the memory allocated for temp, but with this method, you don't have to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top