2016-08-10 17 views
-2

私のプログラムは、メインメソッドが復帰したときに破損したヒープについてのルーン時例外をスローするようです。私はコピーコンストラクタを含め、これが起こらないように適切な予防策を講じています。なぜ誰がこの現象が起こっているのかを明らかにすることはできますか?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 
} 
+2

toStringはどこに定義されていますか – rscarson

+0

"MyString.h"には何がありますか? – kkm

+1

私は 'malloc'と' free'の代わりに 'new'と' delete'を使うことを勧めます。 – grigor

答えて

0

私は@ user4581301の提案に応じて私のポストを固定しています:

それが生成しますので、あなたの加算演算子オーバーロードを変更sholud新しいオブジェクトを作成し、以下のように、アサイメント演算子のオーバーロードを実装します。

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; 
} 
+0

トピックオフ: '+ ='を使ってここでカバーした '+'を実装する、本当に良いトリックがあります:http://stackoverflow.com/questions/4421706/operator-overloading/4421719#4421719 – user4581301

0

あなたはおよそRule Of Three

暗黙assigment演算子が使用され、古いオブジェクトが破棄されたときに新しいものがすでに解放されたポインタを使用し、後でそれが再びそれを解放しようとし学ばなければなりません。

+0

あなたが正しい可能性が非常に高い。 'test = test +" world ";'は致命的であるかもしれませんが、確かに 'operator ='実装があればそれを見る必要があります。コピーコンストラクタとデストラクタはRule of Threeに準拠しており、代入演算子は見ていません。それまでは、私たちができることは、推測です。 – user4581301

関連する問題