C++:使用std::ifstream读取二进制文件后删除缓冲区/指针时发生访问冲突
C++: Access violation when deleting buffer/pointer after using std::ifstream to read binary file
我对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在内部使用一些指向已分配内存的指针。当您读入结构数据时,成员名称具有一些与程序中实际分配的内存不对应的任意值。您读取二进制数据的方法无效。
相关文章:
- C++尝试深度复制唯一指针时出现内存访问冲突
- 尝试通过共享指针使用变量时读取访问冲突
- 使用智能指针读取访问冲突
- C 指针转换会导致内存访问冲突
- C++:读取 Lambda 捕获的指针时出现访问冲突
- 初始化指针时出现写入访问冲突
- 不能对基于数组的指针使用数组运算符(读取访问冲突)
- C++ - 智能指针 - 访问冲突读取位置0xDDDDDDDD
- 调用指针时违反 C++ Typedef 访问冲突
- 为什么未初始化的指针会导致接近 0 的 mem 访问冲突
- 执行指针时发生C++访问冲突
- C++:使用std::ifstream读取二进制文件后删除缓冲区/指针时发生访问冲突
- 指针未指向 NULL 时的访问冲突
- 指针导致访问冲突
- 在标头中声明指针会导致访问冲突
- C++ - 函数、参数和指针 - 访问冲突
- Std::数组到指针访问冲突错误
- c++类:创建线程的对象+指向函数的指针=访问冲突
- C++指针访问冲突写入位置
- C++ shared_ptr<Base>指针访问冲突