调试断言失败
Debug assertion failure
当我尝试释放数组时,我不断从析构函数中得到这个调试断言失败。答案似乎很简单,但我不太清楚。任何帮助将不胜感激。我是初学者(您可能已经猜到了(,所以一个简单的解释会很可爱:)
// 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
。
在一天结束时,你会成为一个更快乐的人,因为你不必花费数小时来调试自卷容器。
相关文章:
- 尝试使用 std::vector<std::thread时出现静态断言失败错误>
- uint_not_usable_without_attribute在业力规则中使用数字生成器时静态断言失败
- 从 exe 文件 (Visual Studio ) 启动时调试断言失败
- 断言"id < 0"在Qt ActiveX中失败
- 在 CppUnit 中测试中止断言失败
- 使用扫描的调试断言失败
- MS 本机单元测试 - 断言::线程失败不起作用
- 为什么我的Qt程序在断言失败后继续运行?
- 图片不显示,关闭时出错 --> 调试断言失败!表达式:is_block_type_valid(标头>_block_use)
- 访问提升:shared_ptr 主范围外崩溃,断言失败:px != 0.指针的正确用法是什么?
- C++ 调试断言失败 - 矢量下标超出视觉工作室的范围
- 错误:断言失败 (src.type() == CV_8UC1) 在阈值中
- Boost Beast 异步服务器失败,断言失败:(id_ != T::id) 在多个 aync 调用中
- 使用imwrite OpenCV时断言失败
- 调试断言失败的缓冲区!=nullptr
- 使用 ofstream 写入文本文件时断言失败
- OpenCV 错误:相机校准:断言在matrix_wrap.cpp失败
- 提升继续恢复断言失败
- 获取有关调试断言失败的错误:表达式:"(_Ptr_user &(_BIG_ALLOCATION_ALIGNMENT -1)) == 0" &&0
- 打破gdb中失败断言的正确方法是什么