Heap Corruption on member assignment overload?

634 views c++
1

Have been struggling with this problem for a while and would like some insight. I have overloaded the addition and assignment operators for a created class. The assignment operator seems to return fine, but then the next line exits with this error:

HEAP CORRUPTION DETECTED: after Normal block (#160) at 0x012CA7D0. CRT detected that the application wrote to memory after end of heap buffer.

My code for both operators are below:

HSString& HSString::operator =(const HSString& argStr) {

    if (this != &argStr) {
        delete[] str;
        end = argStr.end;
        cap = argStr.cap;

        if (end > 0) {
            str = new char[end];
            for (int i = 0; i <= end; i++) {
                str[i] = argStr.str[i];
            }
       }
    }
    return *this;
}


const HSString HSString::operator +(const HSString& strOne)const {

    HSString temp;

    temp.end = end + strOne.end;
    temp.cap = cap + strOne.cap;

    temp.str = new char[cap];

    for (int i = 0; i < end; i++) {
        temp.str[i] = str[i];
    }
    for (int i = 0; i <= strOne.end; i++) {
        temp.str[i + end] = strOne.str[i];
    }
    return temp;
}

After member assignment operator is returned with a deep copy the error is then executed.

answered question

You need to post a Minimal, Complete, and Verifiable example, since I can see multiple issues with just the small sample you posted. Your str is not set to nullptr if end <= 0, thus if your destructor attempts to do delete [] str;, the behavior becomes undefined. Also for operator + to work correctly requires us to see your copy constructor, assignment operator, and destructor, not just a snippet of one of those functions.

1 Answer

4

for (int i = 0; i <= end; i++)

This creates an overflow. Because in C++ arrays start at Index 0 if your declare an array with 5 elements the index range is from 0 to 4. So if you create an array of size end your Indexes range from 0 to end - 1. That means you need to check for i < end

EDIT: this propably applies to for (int i = 0; i <= strOne.end; i++) too despite i do not know the implementation of HSString

posted this

Have an answer?

JD

Please login first before posting an answer.