C++ Corrupted Heap
C++ Corrupted Heap
当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;
}
你必须学习三法则
使用隐式赋值操作符,当旧对象被销毁时,新对象使用已经释放的指针,然后再尝试释放它。
相关文章:
- 为什么我的 heap.h 文件给我一个LNK2001错误?
- 当为可变性配置时,boost::heap::d_ary_heap 保留的额外 std::list 的目的是什么?
- 为什么我会收到"Run-Time Check Failure #2 - Stack around the variable 'pr' was corrupted"错误?
- 了解 Linux 虚拟内存:valgrind 的 massif 输出显示了有和没有 --pages-as-heap 的主要差异
- 从 MSVC14 切换到 MSVC16 会导致"compiler is out of heap space (C1060)"错误
- 庞大的初始化列表,如何修复"fatal error C1060: compiler is out of heap space"
- 在析构函数中调用"delete"运算符时"compiler is out of heap space"编译器错误
- 在 boost::heap::p riority_queue 中推送结构对象时出错
- 如何修复初始化后'stack around variable was corrupted.'变量未更改为分配的值
- 了解 glibc 错误"corrupted size vs. prev_size"
- QCoreApplication on the heap
- 用于创建Min-Heap的算法
- 为什么这段代码会导致"heap corruption detected"?
- Min-Heap,基于零的数组C
- STL for Fibonacci Heap?
- Windows heap corruption C++C
- C 将HEAP对象插入std ::用insert()插入映射,而另一个则存在删除新的对象
- 在windbg中"!heap -h"输出中"Internal"的含义是什么?
- OpenCV HOGDescriptor HEAP crash
- C++ Corrupted Heap