2016-08-10 2 views
-2

main 메서드가 반환 될 때 내 프로그램이 손상된 힙에 대한 룬 시간 예외를 throw하는 것으로 보입니다. 복사 생성자를 포함하여 이러한 일이 발생하지 않도록 적절한 예방 조치를 취했습니다. 누가 이런 일이 일어나고 있는지에 대해 밝힐 수 있습니까?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 새 객체를 만들고 다음과 같이 assigment 연산자 오버로드를 구현하십시오.

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

암시의 할당은 연산자를 사용 배울 필요하고 기존 개체가 소멸 새 이미 사용 포인터를 해제하고 나중에 다시 그것을 해제하려고 시도합니다.

+0

당신이 옳을 가능성은 매우 높습니다. . 'test = test + "world"; "는 치명적일 수 있지만 반드시 operator = implementation이 있는지 확인해야합니다. 복사 생성자와 소멸자는 규칙 3을 준수하며 할당 연산자는 보지 못했습니다. 그때까지 우리가 할 수있는 최선은 추측입니다. – user4581301