2017-06-22 228 views
0

當我嘗試釋放數組時,我不斷從析構函數獲取調試斷言失敗。答案似乎很簡單,但我無法弄清楚。任何幫助,將不勝感激。我是一個初學者(正如你可能已經猜到了),這樣一個簡單的解釋將是可愛:)調試斷言失敗

// Class definitions 
class Book { 
public: 
    string title; 
    string author; 
    int pubYear; 
}; 

class Library { 
private: 
    Book *myBooks; 
    static int getBookIndex; 
    static int maxAmountOfBooks; 
    static int currentAmountOfBooks; 
public: 
    void addBook(Book myBook); 
    Book getBook(void); 
    void showBooks(Library myLib); 
    Library(); 
    ~Library(); 
}; 

// Constructor 
Library::Library() { 
    // Collecting user input 
    cout << "Number of Books: "; 
    cin >> maxAmountOfBooks; 
    cout << endl; 
    // Dynamically allocating memory 
    this->myBooks = new Book[maxAmountOfBooks]; 
    cout << "Dynamically allocated library..." << endl; 
} 

// Destructor 
Library::~Library() { 
    // Freeing the dynamically allocated memory 
    delete this->myBooks; 
    cout << "Freed dynamically allocated library..." << endl; 
} 

// Main 
void main() { 
    // Creating a Book object 
    Book HarryPotter; 
    // Filling Book object fields 
    HarryPotter.title = "Harry Potter"; 
    HarryPotter.author = "JK Rowling"; 
    HarryPotter.pubYear = 1997; 
    // Printing out the Book object fields 
    cout << "Title: " << HarryPotter.title << endl; 
    cout << "Author: " << HarryPotter.author << endl; 
    cout << "Publication Year: " << HarryPotter.pubYear << endl << endl; 

    // Creating a Library object 
    Library myLib; 
    // Callling Library member functions 
    myLib.addBook(HarryPotter); 
    Book retBook = myLib.getBook(); 
    // Printing out the Book object fields 
    cout << "Title: " << retBook.title << endl; 
    cout << "Author: " << retBook.author << endl; 
    cout << "Publication Year: " << retBook.pubYear << endl << endl; 
} 
+2

你正在釋放一個數組:'delete this-> myBooks' ==>'delete [] this-> myBooks'。 – CompuChip

+0

請發表[mcve]:你的不完整,*因爲'addBook'和'getBook'的代碼缺失。它不是*最小的,*因爲'showBooks'永遠不會被調用。 – Angew

+3

使用std :: vector。如果你新增了[],你必須刪除[]。 – 2017-06-22 11:38:20

回答

5

一切你new[]必須delete[]delete是不夠的。

但這樣的建議比較重要的一塊:

開始使用在標準庫,而不是手動使用動態內存分配和祈禱它的工作原理容器。出於某種原因他們在標準庫中,使用它們。在這種情況下爲std::vector

在一天結束時,您將會變得更快樂,因爲您不必花費數小時來調試自卷容器。

+0

是的,很好的建議,但它對於一個新的程序員來解決這些問題本身也是有價值的。畢竟,你不能保證程序員永遠不需要使用舊式代碼的舊代碼庫。 – 2017-06-22 15:02:19