Search code examples
c++destructorheap-corruption

I don't know why it occurs heap corruption(about memory allocation problem)


it's course's one of project and its goal is to make fully-worked MyString Class. Until made destructor method, it was worked well. but in main.cpp, when i tried to use these method i made, it occurs heap corruption. i thought the problem comes up from order of calling destructor but i couldn't figure out where it occurred.

try to check allocated memory(reverse called order) processing without destructor method(it works)

main.cpp

    void main() {
        MyString a = MyString("HELLOMYNAMEIS");
        char ab[10] = "thisiskrw";
        MyString c = ab;
        a = a + c;
        cout << a;
}

MyString.cpp

MyString::~MyString() {
    delete[] str_;
}

MyString operator+(const MyString& lhs, const MyString& rhs) {
    MyString a(lhs);
    MyString b(rhs);
    a += b;
    cout << a;
    return a;
}

MyString& MyString::operator+=(const MyString& str) {
    int i = 0;
    if (this->capacity() < (this->length_ + str.length_)) {
        char* temp = new char[this->length_ + str.length_+1];
        memset(temp, '\0', this->length_+str.length_+1);
        strcpy(temp, this->str_);
        for (int i = 0; i < str.length_; i++) {
            temp[(this->length_) + i] = str.str_[i];
        }
        temp[this->length_ + str.length_] = '\0';
        strcpy(this->str_,temp);
        this->length_ = this->length_ + str.length_;
        delete[] temp;
    }
    else {
        for (int i = 0; i < str.length_; i++) {
            this->str_[(this->length_) + i] = str.str_[i];
        }
        this->length_ = this->length_ + str.length_;
    }
    return *this;
}

it will print string inside MyString object.


Solution

  • You forgot to write this->str_ = temp; anywhere. You just try to write the longer string into the shorter space.

    strcpy(this->str_,temp);
    this->length_ = this->length_ + str.length_;
    delete[] temp;
    

    Should be

    delete [] this->str_;
    this->str_ = temp;