【发布时间】:2016-06-04 14:41:19
【问题描述】:
我试图让一些代码工作,它使用一个类来设置和管理共享内存,并从我的主程序调用该类的一个对象。所有代码都直接在我的 main() 中时有效,但是当我在一个类中设置它并实例化该类的一个对象时,我得到一个段错误。
我不知道为什么或如何解决它?
这里的第一个示例显示了在我的 main() 函数中没有问题的示例:
#include <boost/interprocess/managed_shared_memory.hpp>
using namespace boost::interprocess;
typedef struct teststruct {
int testint=9;
};
typedef std::pair<teststruct, int> memsh_teststruct;
int main(int argc, char *argv[])
{
printf("inMain0\n");
struct shm_remove
{
shm_remove() { shared_memory_object::remove("testShare"); }
~shm_remove(){ shared_memory_object::remove("testShare"); }
} remover;
//Construct managed shared memory
managed_shared_memory segment(create_only, "testShare", 65536);
teststruct myTeststruct;
memsh_teststruct *inst_teststruct;
inst_teststruct = segment.construct<memsh_teststruct>
("name_myTeststruct")
(myTeststruct, 0);
printf("construct_ptr: %p \n", &inst_teststruct->first);
inst_teststruct->first.testint = 1234;
printf("construct_val: %d\n", inst_teststruct->first.testint);
int mainInt;
printf("inMain1\n");
mainInt = inst_teststruct->first.testint;
printf("mainInt: %d\n", mainInt);
printf("inMain2\n");
}
输出看起来不错,像这样:
construct_ptr: 0x7f0d41834118
construct_val: 1234
inMain0
inMain1
mainInt: 1234
inMain2
这是设置完全相同的共享内存的第二个示例,但使用了一个类。
#include <boost/interprocess/managed_shared_memory.hpp>
using namespace boost::interprocess;
typedef struct teststruct {
int testint=9;
};
typedef std::pair<teststruct, int> memsh_teststruct;
class testclass{
public:
testclass();
bool something(int in);
teststruct myTeststruct;
memsh_teststruct *inst_teststruct;
};
testclass::testclass()
{
struct shm_remove
{
shm_remove() { shared_memory_object::remove("testShare"); }
~shm_remove(){ shared_memory_object::remove("testShare"); }
} remover;
//Construct managed shared memory
managed_shared_memory segment(create_only, "testShare", 65536);
inst_teststruct = segment.construct<memsh_teststruct>
("name_myTeststruct")
(myTeststruct, 0);
printf("construct_ptr: %p \n", &inst_teststruct->first);
inst_teststruct->first.testint = 1234;
printf("construct_val: %d\n", inst_teststruct->first.testint);
}
int main(int argc, char *argv[])
{
printf("inMain0\n");
int mainInt;
testclass testclassObj;
printf("inMain1\n");
mainInt = testclassObj.inst_teststruct->first.testint;
printf("mainInt: %d\n", mainInt);
printf("inMain2\n");
}
但是第二个例子有段错误,这是输出:
inMain0
construct_ptr: 0x7fa222d37118
construct_val: 1234
inMain1
Segmentation fault (core dumped)
... 那么为什么要调用
mainInt = testclassObj.inst_teststruct->first.testint;
从 main() 导致段错误?
我还尝试了一些其他变体,例如在我的类中定义其他函数以与共享内存变量进行交互,并且它也会出现段错误。
如果我不得不猜测发生了什么,我感觉共享内存正在关闭或在我预期之前关闭,可能是在退出 testclass() 构造函数之后。但是,我不知道避免这种情况的正确方法,以便在清理整个 testclassObj 对象时从 main() 返回时关闭共享内存。
另一方面,也许我完全错了?
谢谢, 乙
编辑: EDIT2:最后一次编辑被删除,我的错误无关紧要,由于我在 Sean 的回答中对评论线程做了一些愚蠢的事情。
【问题讨论】:
标签: c++ class boost segmentation-fault boost-interprocess