_block_type_is_valid(phead-nblockuse)因为删除命令

时间:2014-09-02 03:58:11

标签: c++ visual-studio-2012 memory-leaks runtime-error placement-new

ifstream ifile("Library.dat",ios::in|ios::binary);

Book *book_obj=new Book; //Book is the class name
if(ifile)
 {
    while(ifile.read((char*)book_obj,sizeof(Book)))
     book_obj->Display_BookDetails();
}
ifile.close();

delete book_obj; //Runtime Error is coming here.If I comment out this, then it works fine

我正在从名为Library.dat的文件中读取内容。当我执行上面的代码时,我得到运行时错误访问冲突读取位置0x004B9B44。评论删除book_obj完全正常。如何删除book_obj以阻止内存泄漏。

1 个答案:

答案 0 :(得分:0)

您的课程包含非POD会员。您不能将结构作为字节块读取而不会遇到问题。您必须通过创建自己的std::istream& operator>>(std::istream&, Book&)函数自行序列化:

std::istream& operator>>(std::istream& is, Book& b)
{
    // extract individually into b's data members
}

现在你可以做到:

while (ifile >> book_obj)
{
    book_obj->Display_BookDetails();
}