私のプログラムは、メインメソッドが復帰したときに破損したヒープについてのルーン時例外をスローするようです。私はコピーコンストラクタを含め、これが起こらないように適切な予防策を講じています。なぜ誰がこの現象が起こっているのかを明らかにすることはできますか?C++破損したヒープ
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はどこに定義されていますか – rscarson
"MyString.h"には何がありますか? – kkm
私は 'malloc'と' free'の代わりに 'new'と' delete'を使うことを勧めます。 – grigor