调试断言失败

Debug assertion failure

本文关键字:失败 断言 调试      更新时间:2023-10-16

当我尝试释放数组时,我不断从析构函数中得到这个调试断言失败。答案似乎很简单,但我不太清楚。任何帮助将不胜感激。我是初学者(您可能已经猜到了(,所以一个简单的解释会很可爱:)

// 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;
}

new[]的一切你都必须delete[]delete是不够的。

但更重要的建议

开始使用标准库中的容器,而不是手动使用动态内存分配并祈祷它有效。它们在标准库中是有原因的,请使用它们。 在这种情况下std::vector

在一天结束时,你会成为一个更快乐的人,因为你不必花费数小时来调试自卷容器。