Question

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;
}
Was it helpful?

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).

OTHER TIPS

in your function getData()

you allocate the variable file on the stack.

mapped_file_source file;

it means that the object is automatically destroyed at the end of the function scope.

however you return the adress of this object with this line:

return &file;

you should rather allocate file on the heap with the keyword new:

mapped_file_source * file = new mapped_file_source() ;

and don't forget to manually delete it with keyword delete in the main() function, when you no longer need the object.

delete file;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top