C++ Corrupted Heap

C++ Corrupted Heap

本文关键字:Heap Corrupted C++      更新时间:2023-10-16

当main方法返回时,我的程序似乎抛出了一个关于损坏堆的运行时异常。我已经采取了适当的预防措施来避免这种情况发生,包括复制构造函数。有人能解释一下为什么会这样吗?

MyString.cpp

#include "MyString.h"
#include <cstdio>
#include <Windows.h>
MyString::MyString() {
    str = (char*)malloc(sizeof(char));
    *str = '';
}
MyString::MyString(char* src) {
    int size = sizeof(char)*(strlen(src) + 1);
    str = (char*)malloc(size);
    strcpy_s(str, size, src);
}

MyString MyString::operator+(char* add) {
    int addSize = sizeof(char)*strlen(add);
    int fullSize = sizeof(char)*(strlen(str) + 1) + addSize;
    str = (char*)realloc(str, fullSize);
    char* temp = str;
    temp += strlen(str);
    strcpy_s(temp, addSize + 1, add);
    return *this;
}
MyString::~MyString() {
    if (str)
        free(str);
}
MyString::MyString(const MyString &arg) {
    int size = sizeof(char) * (strlen(arg.str) + 1);
    str = (char*)malloc(size);
    strcpy_s(str, size, arg.str);
}

main.cpp

#include <iostream>
#include "MyString.h"
using namespace std;

int main(int argc, char *argv[]) {
    MyString test = MyString("hello!");
    test = test + " world";
    cout << test.toString() << endl;
    cout << strlen(test.toString()) << endl;
    system("pause");
    return 0; //runtime error here
}

我正在根据@user4581301的建议修复我的帖子:

你应该修改你的加法操作符重载,使它产生一个新的对象,并实现赋值操作符重载,像这样:

MyString operator+(char* add) const {
    int thisSize = sizeof(char)*strlen(str);
    int addSize = sizeof(char)*(strlen(add) + 1);
    int fullSize = thisSize + addSize;
    char* tempStr = (char*)malloc(fullSize);
    strcpy_s(tempStr, fullSize, str);
    strcpy_s(tempStr + thisSize, fullSize, add);
    return MyString(tempStr);
}
MyString& operator=(const MyString& assign){
    int assignSize = sizeof(char)*(strlen(assign.str) + 1);
    str = (char*)realloc(str, assignSize);
    strcpy_s(str, assignSize, assign.str);
    return *this;
}

你必须学习三法则

使用隐式赋值操作符,当旧对象被销毁时,新对象使用已经释放的指针,然后再尝试释放它。