5

What I want is to access the data info of an managed shared memory object using a class named ShmObj with the raw pointer to the shared objects as private member, as code blocks below.

My problem is the main program segmentation fault. I guess the absolute raw pointer causes the problem. I tried to change the raw pointer to bi::offset_ptr but doesn't help. Any help is appreciated.

ShmObj.h

#include <string>
#include <boost/interprocess/managed_shared_memory.hpp>
namespace bi = boost::interprocess;

class ShmObj {
public:
    ShmObj() {
        bi::managed_shared_memory segment(bi::open_only, "shm");
        pNum = segment.find<int>("Number").first;
    }
    int getNumber() {return *pNum;}
    virtual ~ShmObj() {}

private:
    int* pNum;
};

main.cpp

#include "ShmObj.h"
#include <iostream>

int main() {
    ShmObj X;
    std::cout << X.getNumber() << std::endl;
}

1 Answer 1

4

Your shared memory segment is destructed at the end of the constructor... Move it to a field to extend its lifetime:

#include <string>
#include <boost/interprocess/managed_shared_memory.hpp>
namespace bi = boost::interprocess;

class ShmObj {
public:
    ShmObj() 
      : segment(bi::open_or_create, "shm", 32ul*1024),
        pNum(0)
    {
        pNum = segment.find_or_construct<int>("Number")(0);
    }

    int getNumber() {
        assert(pNum);
        return *pNum;
    }

    virtual ~ShmObj() {}

private:
    bi::managed_shared_memory segment;
    int* pNum;
};

#include <iostream>

int main() {
    ShmObj X;
    std::cout << X.getNumber() << std::endl;
}
2
  • Why can't we do pNum(segment.find_or_construct<int>("Number")(0)) also in the initializer list?
    – CinCout
    Oct 13, 2014 at 11:38
  • You can, have you tried? Anyways, for anything non-trivial I'd really not do that in the initializer-list unless you have a suitable Rule-Of-Zero resource wrapper to make it exception safe if the construction throws. Consider: paste.ubuntu.com/8552394
    – sehe
    Oct 13, 2014 at 13:04

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.