Следующая программа выделяет память для c
, объекта типа C
, в пространстве отображаемого в память файла. Добавление одного символа к вектору, содержащемуся в c
, изменяет сообщаемый размер вектора с 0 на 18446744073709551520.
#include <iostream>
#include <new>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/offset_ptr.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
using namespace boost::interprocess;
class C;
typedef managed_mapped_file::segment_manager SegmentManager;
typedef allocator<void, SegmentManager> VoidAllocator;
typedef allocator<char, SegmentManager> CharAllocator;
typedef allocator<C, SegmentManager> CAllocator;
typedef offset_ptr<C> CPtr;
class C {
public:
std::vector<char, CharAllocator> data;
C(const VoidAllocator &voidAlloc) : data(voidAlloc) {}
void add_char() {
std::cout << data.size() << std::endl;
data.push_back('x');
std::cout << data.size() << std::endl;
}
};
int main(int argc, char *argv[]) {
boost::filesystem::remove_all("file");
managed_mapped_file segment(create_only, "file", 100000);
VoidAllocator allocator_instance(segment.get_segment_manager());
CAllocator alloc_c(allocator_instance);
CPtr c = alloc_c.allocate_one();
*c = C(allocator_instance);
c->add_char();
return 0;
}
Проблема не возникает, когда c
выделяется в стеке, а не динамически.
C c(allocator_instance);
c.add_char();
Я компилирую код на Debian GNU/Linux stretch с Boost 1.62 и g++ 6.3.0-18 с помощью следующей команды.
g++ -Wall -pthread -lboost_system -lboost_filesystem t.cpp -o t