深度复制结构到 POSIX 共享内存
我有两个结构:
struct bets{
int bets[36];
int last_bet;
}bets
struct board{
int type;
bets *bet;
}board
我创建了一块 sizeof(board)
的 shad 内存。所以,我在共享内存中得到了一个指向 Board 的指针(不要称之为 ptr)。 我确实创建了一个新的board
和bets
结构, board *b
、bets * bts
、...添加了board->bet = bts
。 现在,我将“b”复制到 ptr memcpy(ptr, bts, sizeof(board))
。 我可以访问ptr->type
。 但是当我尝试访问时 ptr->bet->last_bet
,我收到分段错误错误。
我也尝试像这样复制:
board *b;
memcpy(ptr, b, sizeof(board));
bets *bts;
memcpy(ptr->bet, bts, sizeof(bets)).
仍然出现分段错误错误。
如何将两个结构复制到另一个结构中,并且仍然可以访问嵌套结构?
I have two structures :
struct bets{
int bets[36];
int last_bet;
}bets
struct board{
int type;
bets *bet;
}board
I created a chunk of shad memory of sizeof(board)
. So, I got a pointer to the Board in shared memory (lest call it ptr).
I did created a new board
and bets
structure,board *b
, bets * bts
, .... added board->bet = bts
.
Now, I copied the "b" to ptrmemcpy(ptr, bts, sizeof(board))
.
I can access the ptr->type
.
But when I try to accessptr->bet->last_bet
, I get a segmentation-fault error.
I also tried copying like this:
board *b;
memcpy(ptr, b, sizeof(board));
bets *bts;
memcpy(ptr->bet, bts, sizeof(bets)).
Still getting segmentation-fault error.
How can I copy both struct one inside of the other and still have access to the nested one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
标准“深度复制”到共享内存中没有用,因为即使指针指向共享内存段,指针也位于进程的虚拟地址空间本地,并且当另一个进程映射共享内存时不会相同。您需要存储从共享内存段开头开始的偏移量,而不是指针。
size_t
是一个合适的类型。Standard "deep copying" into shared memory is not useful because the pointers, even if they point into the shared memory segment, are local to your process's virtual address space and won't be the same when another process maps the shared memory. Instead of pointers, you need to store offsets from the beginning of the shared memory segment.
size_t
would be an appropriate type.