【发布时间】:2016-08-10 20:26:56
【问题描述】:
当 main 方法返回时,我的程序似乎抛出了一个关于损坏堆的 rune-time 异常。我已经采取了适当的预防措施来避免这种情况发生,包括复制构造函数。谁能解释一下为什么会这样?
MyString.cpp
#include "MyString.h"
#include <cstdio>
#include <Windows.h>
MyString::MyString() {
str = (char*)malloc(sizeof(char));
*str = '\0';
}
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
}
【问题讨论】:
-
toString 定义在哪里
-
“MyString.h”中有什么?
-
我鼓励使用
new和delete而不是malloc和free。 -
应该在
test = test + " world";收到编译器警告,因为" world"是const char *,而不是char *。与MyString test = MyString("hello!");相同 -
通常我会同意@grigor,但是他们稍后使用的
realloc技巧会有点讨厌。
标签: c++ memory malloc free realloc