简体   繁体   中英

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

I'm pretty new to C++ and have encountered a problem regarding memory and pointer managment (is what I think). I was trying to figure out how to write and read binary files and managed to scrap together a sample program, however errors keep appearing when I try to tweak it with my own structure.

Heres my code:

#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;
}

The program works fine if I ignore the buffer's allocated space, however that'll cause memory leaks won't it? I would appreciate it if anyone would take their time to point out the faults in my code or guide me in the correct direction if my approach is wrong.

These statements

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

has no sense. Class std::string internally uses some pointers to allocated memory. When you read in your structure data member name has some arbitrary values that do not correspond to actually allocated memory in the program. Your approach of reading binary data is invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM