2010-03-24 4 views
1

고마워 ++ 프로그램. 다시 고마워!메모리 누수

은 누군가가 제발 도와 주 시겠어요? :/당신은 이벤트 소멸자에 eventName 삭제되지 않습니다

#include <iostream> 
#include <string> 
#include <vld.h> 

using namespace std; 

class Time 
{ 
private: 

    string dayTime; 

    int hour, 
     minute; 

public: 

    Time(int hour, int minute, string dayTime); // constructor 
    Time(); // default constructor 

    void setTime(); 

    // using encapsulation 
    const int getHour() const { return hour; }; 
    const int getMinte() const { return minute; }; 
    string getDayTime() const { return dayTime; }; 

    const int incrementHours(); 
    int incrementMinutes(); 

    friend ostream& operator<<(ostream& out, const Time tObj); // to write the objects attributes 
}; 

class Date 
{ 

private: 
    string month; 
    int  day, 
      year; 

public: 

    Date(string month, int day, int year); 
    Date(const Date& d);// copy constructor 

    Date(); // default constructor 
    virtual ~Date(); 

    void setDate(); 

    string getMonth() const { return month; }; 
    const int getDay() const { return day; }; 
    const int getYear() const { return year; }; 

    friend ostream& operator<<(ostream& out, const Date dObj); // to write the objects attributes 
}; 

class Event 
{ 
private: 

    string eventName, 
      userEvent; 

    struct node 
    { 
     node(); 
     node * nextByName; 
     string eventName; 
    }; 

    node * headByName; 

public: 
    Event(string eventName, const Date &myDate); 
    Event(); 

    virtual ~Event(); 

    void insert(string eventName, const Date &myDate, const Time &myTime); 
    void setEvent(); 

    string getEvent() const { return userEvent; }; 
    void displayByName(ostream& out) const; 

}; 

/***************************************************/ 

Time::Time(int hour, int minute, 
      string dayTime) : minute(minute), 
          hour(hour), 
          dayTime(dayTime) 

{ 
    this->hour = hour; 
    this->minute = minute; 
    strcpy_s((char*)dayTime.c_str(), dayTime.length()+1, dayTime.c_str()); 
} 

Time::Time() : hour(0), 
       minute(0), 
       dayTime(NULL) 
{ 
} 

void Time::setTime() 
{ 
    cout << "Enter the hour: "; 
    cin >> hour; 
    cout << "Enter the minute: "; 
    cin >> minute; 
    cout << "is it P.M. or A.M.? "; 
    cin >> dayTime; 

    this->incrementMinutes(); 
} 

int Time::incrementMinutes() 
{ 
    if (minute <= 0) 
    { 
     minute %= 59; 
    } 
    else if (minute >= 59) 
    { 
     hour++; // we have a new hour 
     minute %= 59; // get the rest of the minutes 
     // it is unlikely that the user will enter a 4-5 digit amount. 
    } 
    this->incrementHours(); 
    return minute; 
} 

const int Time::incrementHours() 
{ 
    if (hour > 12) 
    { 
     hour %= 12; 
     this->incrementHours(); 
    } 
    else if (hour == 0) 
    { 
     hour = 12; 
    } 
    return hour; 
} 


ostream& operator<<(ostream& out, const Time tObj) 
{ 
    if (tObj.getMinte() < 10) 
    { 
      return out << endl << tObj.getHour() << ":" 
         << "0" << tObj.getMinte() << " " 
         << tObj.getDayTime()  << "\n" 
       ; 
    } 
    else 
    { 
     return out << endl << tObj.getHour() << ":" 
         << tObj.getMinte() << " " 
         << tObj.getDayTime() << "\n" 
       ; 
    } 
} 

/*************************************/ 


Date::Date(string month, int day, int year) : month(month), 
                day(day), 
                year(year) 
{ 
    strcpy_s((char*)month.c_str(), month.length()+1, month.c_str()); 
    this->day = day; 
    this->year = year; 
} 

Date::Date() : month(0), 
       day(0), 
       year(0) 
{ 

} 

Date::~Date() 
{ 
} 

Date::Date(const Date &d) : month(d.month), 
          day(d.day), 
          year(d.year) 
{ 

} 

void Date::setDate() 
{ 
    cout << "enter the month: "; 
    cin >> month; 
    cout << "enter the numeric day: "; 
    cin >> day; 
    cout << "enter the numeric year: "; 
    cin >> year; 
    cout << endl; 
} 

ostream& operator<<(ostream& out, Date dObj) 
{ 
    return out << endl << dObj.getMonth() << " " 
         << dObj.getDay() << ", " 
         << dObj.getYear() << "\n" 
       ; 
} 

/*****************************************/ 

Event::Event(string eventName, const Date &myDate) : eventName(eventName), 
                userEvent(userEvent), 
                headByName(NULL) 

{ 
    strcpy_s((char*)eventName.c_str(), eventName.length()+1, eventName.c_str()); 
} 

Event::Event() : eventName(NULL), userEvent(NULL), headByName(NULL) 
{ 
} 

Event::~Event() 
{ 
    node * temp_node = NULL; 
    node * current_node = headByName; 

    while (current_node) 
    { 
     temp_node = current_node->nextByName; 
     delete current_node; 
     current_node = temp_node; 
    } 
} 

void Event::insert(string eventName, const Date &myDate, const Time &myTime) 
// when we insert we dont care about the time, just the name and the date 
{ 
    node * current_node = new node(); 

    if (headByName == NULL) 
    { 
     headByName = current_node; 
     headByName->eventName = eventName; 
    } 
    else 
    { 
     node * search_node = headByName; 
     node * prev_node = NULL; 

     while (search_node != NULL) 
     { 
      prev_node = search_node; 
      search_node = search_node->nextByName; 
     } 
     if (NULL == prev_node) 
     { 
      headByName = current_node; 
     } 
     else 
     { 
      prev_node->nextByName = current_node; 
     } 
      current_node->nextByName = search_node; 
      current_node->eventName = eventName ; 
    } 
} 

void Event::displayByName(ostream& out) const 
{ 
    cout << "Scheduled Events are: " << endl << endl; 
    node * current_node = headByName; 

    while (current_node) 
    { 
     strcpy_s((char*)eventName.c_str(), current_node->eventName.length()+1, current_node->eventName.c_str()); 
     out << eventName.c_str() << endl; 
     current_node = current_node->nextByName; 
    } 
} 

Event::node::node() : nextByName(NULL), eventName(eventName) 
{ 
    strcpy_s((char*)eventName.c_str(), eventName.length()+1, eventName.c_str()); 
} 

void Event::setEvent() 
{ 
    cout << "\n\nEnter a new event! "; 
    cin.getline((char*)userEvent.c_str(), 256); 

} 

/*****************************/ 

int main() 
{ 
    Date dObj("March", 21, 2010); // instaintiate our Date class object by allocating default date paramateres. 
    Event eObj("First Day of Spring", dObj); 
    Time tObj(10,12,"PM"); 

    cout << "default Time is: " << tObj << endl; 
    cout << "default Date is: " << dObj << endl; 

    eObj.insert("First Day of Spring", dObj, tObj); 
    eObj.insert("Valentines Day", Date("February",14,2010), tObj); 
    eObj.insert("New Years Day", Date("Janurary",1, 2011), tObj); 
    eObj.insert("St. Patricks Day", Date("March",17, 2010), tObj); 

    eObj.displayByName(cout); 

    eObj.setEvent(); 
    const char * const theEvent = eObj.getEvent().c_str(); 
    dObj.setDate(); 

    eObj.insert((string)theEvent, dObj, tObj); 
    tObj.setTime(); 

    cout << "Your event: " << theEvent << " is scheduled for: " << endl 
     << dObj << "at" << tObj; 

    eObj.displayByName(cout); 

    cin.ignore(2); 
    return 0; 
} 
+1

당신이 우리에게 준 것은 인터페이스입니다. 인터페이스에서 메모리 누수가 발생하지 않습니다. 구현시 발생합니다.:) – GManNickG

+0

구현으로 재 게시했습니다. – user40120

답변

1

(을이 숙제 질문하지 않습니다). 또한

Event::~Event() 
{ 
delete [] eventName; 

, 당신은 수동 메모리 관리에 너무 많이 의존하고

Time::~Time() 
     { 
      delete[] dayTime; 
        ^missing 
     } 

    Date::~Date() 
     { 
      delete[] month; 
     } 
+0

가지고있을 때 디버그 어설 션 오류가 발생합니다. – user40120

+0

~ ~ 시간과 ~ 날짜에 다른 삭제 []가 있습니다 .... 모두 수정하고 확인하십시오. –

+0

솔직히 delete와 쌍을 이루는 [] 연산자가 삭제와 다른 효과가 있다고 생각하지 않습니다. – user40120

4

. C++의 기능을 사용하지 않고 C 프로그램에 객체 지향 인터페이스를 추가 한 것 같습니다. std::string (이미 하나를 사용하고있는 것으로 보입니다)에 문자열을 저장하고 std::list (EDIT :이 실제로는 std::set) 링크 된 목록을 사용하고 가능한 경우 스택에 개체를 놓으십시오. 당신은이 모든 프로그램에 new 또는 어떤 포인터를 필요가 없습니다.

이 (내 목록의 제안은 아래의 각 event는 별도의 목록을 가지고 있다고 가정합니다. 그 잘못 경우 죄송합니다) 주에서

class Time 
    { 
    private: 

     string dayTime 
      ; 

     int hour, 
      minute 
      ; 

    public: 

     Time(int hour, int minute, string const dayTime); // constructor 
     Time(const Time& myTime); // copy constructor 

     Time(); // default constructor 

     virtual ~Time(); // destructor 

     void setTime(); 

     // using encapsulation 
     const int getHour() const { return hour; }; 
     const int getMinte() const { return minute; }; 
     string const getDayTime() const { return dayTime; }; 

     const int incrementHours(); 
     int incrementMinutes(); 

     friend ostream& operator<<(ostream& out, const Time * tPtr); // to write the objects attributes 
    }; 

    class Date 
    { 

    private: 
     string month; 
     int  day, 
       year; 

    public: 

     Date(const char * month, int day, int year); 
     Date(const Date& d);// copy constructor 

     Date(); // default constructor 
     virtual ~Date(); 

     void setDate(); 

     string const getMonth() const { return month; }; 
     const int getDay() const { return day; }; 
     const int getYear() const { return year; }; 

     friend ostream& operator<<(ostream& out, const Date * dPtr); // to write the objects attributes 
    }; 

    class Event 
    { 
    private: 

     string eventName 
      ; 
     string userEvent; 

     list<string> event_names; 

    public: 
     Event(const char * eventName, const Date &myDate); 
     Event(); 

     virtual ~Event(); 

     void insert(const char * eventName, const Date &myDate, const Time &myTime); 
     void setEvent(); 

     string const getEvent() const { return userEvent; }; 
     void displayByName(ostream& out) const; 

    }; 

...

 Date dPtr("March", 21, 2010); // instaintiate our Date class object by allocating default date paramateres. 
     Event ePtr("First Day of Spring", *dPtr); 
     Time tPtr(10,12,"PM"); 

귀하의 코드가 매우 장황를 ...

+0

글쎄, 고마워. 나는 그것을 고쳤지만 Time Copy Ctor와 Dtor에 오류가 있습니다. – user40120

+0

@lampshade : 예, 클래스 정의 만 편집했습니다. 문자열 관리 코드를 제거해야합니다. 복사 생성자와 소멸자를 완전히 삭제하면 충분합니다. 이 프로그램에서 소멸자를 정의 할 필요는 없을 것입니다. – Potatoswatter

+0

네, 그 모든 엉망이 됐어. 내일 늦게 내 시간대에서 시험해 보겠다. 모든 도움에 감사드립니다! =) – user40120

1

이 생성자 (strcpy_s은 표준 함수 strcpy과 유사 함)를 사용하는 것은 잘못된 것입니다.

이미 이니셜 라이저 목록에 minute, hourday을 초기화 했으므로 생성자 본문에 다시 할당하지 않아도됩니다.

c_str()는 읽기 전용 그래서 잠재적 위험을 통해 쓰기를 시도하는 제어 문자열 (아마도 복사)를 반환합니다.

나는 명백한 메모리 누수를 볼 수 있지만, 이것은 예상치 못한 문제의 원인 일 수 있습니다. 당신의 Time 생성자에서

Time::Time(int hour, int minute, 
       string dayTime) : minute(minute), 
           hour(hour), 
           dayTime(dayTime) 

    { 
     this->hour = hour; 
     this->minute = minute; 
     strcpy_s((char*)dayTime.c_str(), dayTime.length()+1, dayTime.c_str()); 
    } 
0

당신은 (단지 비효율적)를 두 번 hourminute를 초기화하는있다, 그러나 당신은 strcpy와 함께 dayTime를 초기화하는있다. dayTime 이후

Time::Time(): hour(0), minute(0) 
{} 

은 문자열이고 당신을 위해 초기화 기본값이됩니다 :

Time::Time(int hour, int minute, string dayTime): 
    minute(minute), hour(hour), dayTime(dayTime) 
{} 

는 또한 기본 생성자 만이 필요합니다에만이 필요합니다.

당신은 Date 생성자에서 유사한 문제가있다.