【问题标题】:I don't know why it occurs heap corruption(about memory allocation problem)不知道为什么会发生堆损坏(关于内存分配问题)
【发布时间】:2019-10-13 14:02:46
【问题描述】:

这是课程之一,其目标是制作完整的 MyString 类。在制作析构函数之前,它运行良好。但是在 main.cpp 中,当我尝试使用我制作的这些方法时,会发生堆损坏。我以为问题出在调用析构函数的顺序上,但我不知道它发生在哪里。

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

ma​​in.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 对象中打印字符串。

【问题讨论】:

  • 当您需要分配更多内存时,请查看operator+= 中的最后三行。考虑一下你刚刚在那个函数中做了什么,以及那三行应该做什么。
  • 如果你没有复制构造函数和赋值运算符,你也可以考虑使用它们,这样你就不会重复删除东西。阅读三法则。

标签: c++ destructor heap-corruption


【解决方案1】:

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

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

应该是

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 2019-09-23
    • 2021-06-16
    相关资源
    最近更新 更多