Search code examples
c++memory-mapped-files

Data are lost after memory mapped file is returned


When I am returning a pointer to my memory mapped file or I return my file in a structure, data are lost outside of function scope. What should my function return.

#include <iostream>
#include <fstream>
#include <boost/iostreams/device/mapped_file.hpp>
using namespace std;
using namespace boost::iostreams;

struct data
{
public:

    long long timestamp;
    double number1;
    double number2;
};
int fileSize(ifstream &stream){
    stream.seekg(0, ios_base::end);
    return stream.tellg();
}

mapped_file_source * getData(const string& fin){
    ifstream  ifs(fin, ios::binary);
    mapped_file_source file;
    int numberOfBytes = fileSize(ifs);
    file.open(fin, numberOfBytes);

    // Check if file was successfully opened
    if (file.is_open()) {
        return &file;
    }
    else {
        throw - 1;
    }
}

int main()
{
    mapped_file_source * file = getData("data/bin/2013/6/2/AUD_USD.bin");
    struct data* raw = (struct data*) file->data();
    cout << raw->timestamp;
}

Solution

  • You cannot return a pointer to a local stack object. Your compiler should have issued a warning. Once the function is done, the object on the stack will lose scope, be destroyed and your pointer is invalid.

    You need to put your variable on the heap by creating it with new or you need to make a copy (although I'm not sure if the class is copyable).