C++:使用std::ifstream读取二进制文件后删除缓冲区/指针时发生访问冲突

C++: Access violation when deleting buffer/pointer after using std::ifstream to read binary file

本文关键字:指针 访问冲突 缓冲区 std 使用 ifstream 读取 C++ 二进制文件 删除      更新时间:2023-10-16

我对C++还很陌生,遇到了内存和指针管理方面的问题(我就是这么认为的)。我试图弄清楚如何编写和读取二进制文件,并设法将一个示例程序拼凑在一起,但当我试图用自己的结构调整它时,错误不断出现。

这是我的代码:

#include "stdafx.h"
#include <fstream>
#include <iostream>
struct Data
{
std::string name;
unsigned int age;
};
int _tmain(int argc, _TCHAR* argv[])
{
/*  Here is the part which I only ran the first time to write the file
std::ofstream oFile("foo.bin", std::ios::out | std::ios::binary);
Data data;
data.name = "Brian";
data.age = 32;
oFile.seekp(0);
oFile.write((char*)&data, sizeof(Data));
oFile.close();
*/
std::ifstream iFile("foo.bin", std::ios::in | std::ios::binary);
Data* buffer = new Data;
iFile.read((char*)buffer, sizeof(Data));
iFile.close();
std::cout << buffer->name.c_str() << std::endl;
delete buffer;
return 0;
}

如果我忽略缓冲区的分配空间,程序会正常工作,但这会导致内存泄漏,不是吗?如果有人能花时间指出我代码中的错误,或者在我的方法错误的情况下指导我朝着正确的方向前进,我将不胜感激。

这些语句

iFile.read((char*)buffer, sizeof(Data));
//...
std::cout << buffer->name.c_str() << std::endl;

毫无意义。类std::string在内部使用一些指向已分配内存的指针。当您读入结构数据时,成员名称具有一些与程序中实际分配的内存不对应的任意值。您读取二进制数据的方法无效。