创建/初始化共享内存中的对象(由mmap()打开)
我创建了共享内存并使用以下代码映射了我的对象:
shmfd = shm_open(SHMOBJ_PATH, O_CREAT | O_EXCL | O_RDWR, S_IRWXU | S_IRWXG);
ftruncate(shmfd, shared_seg_size);
bbuffer = (boundedBuffer *)mmap(NULL, shared_seg_size, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
现在我需要初始化并向 bbuffer 添加项目或从 bbuffer 中删除项目。当我尝试添加/删除时,出现“分段错误:11”,这表明程序访问了未分配的内存位置。我可以做什么来解决这个问题?
I created my shared memory and mapped my object with following code:
shmfd = shm_open(SHMOBJ_PATH, O_CREAT | O_EXCL | O_RDWR, S_IRWXU | S_IRWXG);
ftruncate(shmfd, shared_seg_size);
bbuffer = (boundedBuffer *)mmap(NULL, shared_seg_size, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
Now I need to initialize and add/remove items to/from bbuffer. When I try to add/remove, I get Segmentation Fault: 11, which indicates the program accessed a memory location that was not assigned. What can I do to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个疯狂的猜测:
void*
和 32 位位int
可能发生的情况是,编译器默认将
mmap
作为返回int
的值,将其转换为指针,从而与更高层的指针发生冲突。顺序位。切勿对
malloc
或mmap
等函数的返回值进行强制转换,并始终认真对待编译器的警告。A wild guess:
mmap
includedvoid*
and 32 bitint
What could happen there is that the compiler takes
mmap
as returningint
by default, casts this into a pointer and by that clashes the higher order bits.Never cast return values from functions such as
malloc
ormmap
, and always take the warnings of your compiler seriously.