2014-10-30 57 views
0

我設法隔離了一個使程序崩潰的錯誤,但我還沒弄清楚這個問題。我想問題在於調用對象lookProfile和lookContacts的默認構造函數,因爲一旦我刪除了這些行,程序就能順利運行。崩潰,可能是由於構造函數或析構函數中的某個問題

這是主要的。

#include <iostream> 
#include <fstream> 
#include "profile.h" 
#include "contact.h" 
#include <sstream> 

using namespace std; 

void Query(profile* &lsp,int,ofstream& outt); 

int main() 
{ 
    ifstream inn; 
    ofstream outt; 

    char resp; 

    profile *listp; 

    int length=0; 

    listp = new profile[50]; 

    inn.open("profiles.txt");  // retrieve profiles 
    retrieveProfiles(inn,listp,length); 
    inn.close(); 

    cout << "Do you want to add your profile or to look for someone? (A/L)"; 
    cin >> resp; 

    if(resp=='A') 
    { 
     outt.open("profiles.txt",ios::app); 
     addProfile(outt); 
     outt.close(); 
    }else if(resp=='L') 
    { 
     outt.open("contacts.txt",ios::app); 
     Query(listp,length,outt); 
     outt.close(); 
    } 
    else 
     cout << "Wrong Input"; 

    return 0; 
} 

void Query(profile* &lsp,int length,ofstream& outt) 
{ 
    const int THRESHOLD = 3; 

    string str; 
    int num,numvec[3]; 
    int *overthreshold; 
    int countOver=0; 
    char dis; 
    profile lookProfile; 
    contact lookContact; 
} 

這些都是類個人資料的專用成員和執行構造函數和析構函數:

private: 
    std::string name; 
    std::string surname; 
    int age; 
    std::string icolor; 
    int height; 
    std::string homeTown; 
    std::string livingTown; 
    std::string *hobby; 
    int lenghob; 
    int ID; 

profile::profile() //ctor 
{ 
    name=""; 
    surname=""; 
    age=0; 
    height=0; 
    icolor=""; 
    homeTown=""; 
    livingTown=""; 
    lenghob=0; 
    ID=0; 
} 

profile::~profile() //dtor 
{ 
    delete [] hobby; 
} 

這些都是類接觸的私有成員和執行構造函數和析構函數:

private: 
    int date[3]; 
    std::string time; 
    std::string place; 
    std::string address; 
    std::string *keywords; 
    int lengthkw; 

contact::contact()  //ctor 
{ 
    for(int i=0;i<3;i++) 
     date[i]=1; 

    time="12:00-13:00"; 
    place=""; 
    address=""; 
    lengthkw=0; 
} 

contact::~contact() 
{ 
    delete [] keywords; //dtor 
} 

在此先感謝。

+0

我猜你的類違反[Rule of Three](http://stackoverflow.com/questions/4172722),因爲你已經向我們顯示了析構函數,但沒有複製構造函數或賦值操作符。事實上,他們似乎並沒有初始化「嗜好」和「關鍵字」。使用'std :: vector'而不是嘗試玩弄原始指針。 – 2014-10-30 17:28:38

+0

'一旦我刪除這些行程序運行順利.'它不運行「順利」。你的代碼現在沒有實現這兩個函數就會發生內存泄漏,並且可以通過簡單的賦值輕鬆破解。 – PaulMcKenzie 2014-10-30 17:56:39

回答

3

您已將hobbykeywords定義爲std::string指針,但您並未通過致電new來初始化它們。但是,在你的析構函數中,你打電話給delete。由於它們是垃圾,你會得到未定義的行爲,所以可能是崩潰。

+0

非常感謝!這個問題是由此創建的。所以,對於未來,我是否總是必須初始化一個指針,即使我假設它是空的(就像這樣)? – RDGuida 2014-10-31 10:10:13

+0

將它初始化爲某些東西是個好習慣。如果你想延遲分配它,那麼只需將它設置爲null('keywords = nullptr')。如果你想要有一個關鍵字數組,然後只使用一個矢量('std :: vector >關鍵字'),這會使內存管理和指針問題消失。 – Sean 2014-10-31 10:13:48