2017-06-22 5 views
0

配列を解放しようとすると、このデバッグアサーションの失敗がデストラクタから引き続き発生します。答えは本当にシンプルなようですが、私はそれを理解できません。どんな助けもありがとう。 (ご想像の通り)私はそう簡単な説明は、あなたがnew[]あなたがdelete[]必要があり、素敵な:)アサーションのデバッグのエラー

// 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を使用します。あなたが新しい[]の場合、[]を削除する必要があります。 –

答えて

5

すべて、deleteが十分ではないだろう初心者です。

しかし、アドバイスの仕方がより重要な部分:

スタート代わりに、手動で動的なメモリ割り当てを使用し、それが動作祈るの標準ライブラリにあるコンテナを使用しました。彼らは理由のために標準的な図書館にいます、それらを使用してください。この場合はstd::vectorです。

セルフロールコンテナのデバッグに時間を費やす必要がないため、一日の終わりには幸せな人になります。

+0

はい、いいアドバイスですが、新しいプログラマーがこのような問題に苦労することは、それ自体にとっても有益です。結局のところ、プログラマーは古いスタイルのイディオムが盛り込まれた古いコードベースで作業する必要はないということを保証することはできません。 –

関連する問題