I get invalid read / segmentation fault errors using boost::iterator_range.
Where is my data going out of scope and how can I prevent that from happening?
Here is some code to reproduce the problem:
#include <iostream>
#include <vector>
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/range.hpp>
#include <boost/range/iterator_range.hpp>
These are my types:
typedef double Value;
typedef std::vector<Value> vValue;
typedef boost::iterator_range<std::vector<Value>::iterator> rValue;
Utility function:
void print_range(const rValue &r) {
for(rValue::difference_type i = 0; i < r.size(); ++i) std::cout << r[i] << " ";
std::cout << std::endl;
}
This is an object that stores a cache of all data.
class MyDataObject { // This object stores ALL DATA.
private:
vValue data;
public:
void setData(vValue data) {
this->data = data;
}
vValue &getData() {
return data;
}
};
Data segments are then created as a subset of all data using boost::iterator_range.
class DataSegment { // This object points to a subset of all data using boost::iterator_range
private:
rValue data;
public:
void setData(rValue data) {
this->data = data;
}
rValue& getData() {
return data;
}
};
Actual database implementation:
class DB { // The database caches ALL DATA and then returns a subset using boost::iterator_range when asked for.
private:
std::map<std::string, MyDataObject> cache;
public:
DB() {
//
}
MyDataObject loadIntoCache(std::string key) {
vValue data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
MyDataObject obj;
obj.setData(data);
cache[key] = obj;
return obj;
}
boost::shared_ptr<DataSegment> getMemoryEfficientSubset() {
MyDataObject obj = loadIntoCache("bar"); // If bar is not in cache, load it.
rValue data = obj.getData();
boost::shared_ptr<DataSegment> segment(new DataSegment());
rValue out = boost::make_iterator_range(data.begin() + 2, data.begin() + 7);
segment->setData(out);
return segment;
}
};
Test code:
int main() {
DB *db = new DB();
boost::shared_ptr<DataSegment> segment = db->getMemoryEfficientSubset();
print_range(segment->getData()); // ERROR: segfault within print_range. Valgrind says "Invalid read of size 8"
delete db;
return 0;
}
The iterator range ultimately stored in
*segmentis associated withdata, which is local to the call. Presumably you meantloadIntoCacheto return aMyDataObject&(initialized from e.g.cache[key] = obj), which would remain valid as long as the cache is. Make also sure thatobjis a reference to the result of the call toloadIntoCache, not a copy, and similarly fordataand the result of the callobj.getData().