[英]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在內部使用一些指向已分配內存的指針。 當您讀入結構數據時,成員名稱具有一些與程序中實際分配的內存不對應的任意值。 您讀取二進制數據的方法無效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.