c++ - 我不知道为什么会发生堆损坏(关于内存分配问题)

标签 c++ destructor heap-corruption

这是类(class)的项目之一,其目标是制作完整的 MyString 类。在制作析构函数方法之前,它运行良好。但是在 main.cpp 中,当我尝试使用我制作的这些方法时,它发生了堆损坏。我认为问题出在调用析构函数的顺序上,但我无法弄清楚它发生在哪里。

尝试检查分配的内存(逆调用顺序) 没有析构方法的处理(有效)

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

它将在 MyString 对象中打印字符串。

最佳答案

你忘了在任何地方写this->str_ = temp;。您只需尝试将较长的字符串写入较短的空间即可。

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

应该是

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

关于c++ - 我不知道为什么会发生堆损坏(关于内存分配问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56335482/

相关文章:

c++ - 删除包含结构的 vector 的 vector

带地址的 C++ 数组迭代 - 堆损坏

c++ - ifstream::read 不断返回不正确的值

c# - 同一文件中的文本和二进制数据

c++ - cmake - 从函数而不是全局范围调用 find_package 时出现奇怪的副作用

c++ - 方程中中间体的破坏

c++ - 为模板类重载 operator[] - C++

c++ - 关于 C++ 析构函数

c++ - 两个 DLL 之间的堆损坏

c++ - 使用智能卡签名时指定给 RtlFreeHeap 的地址无效 (C++)