这让我非常沮丧。我只是试图创建一个共享内存缓冲区类,该类使用通过Boost.Interprocess创建的共享内存来读取/存储数据。我写了下面的测试功能boost.interprocess中共享内存中的memcpy的问题
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
using namespace std;
using namespace boost::interprocess;
int main(int argc, char* argv[]) {
shared_memory_object::remove("MyName");
// Create a shared memory object
shared_memory_object shm (create_only, "MyName", read_write);
// Set size for the shared memory region
shm.truncate(1000);
// Map the whole shared memory in this process
mapped_region region(shm, read_write);
// Get pointer to the beginning of the mapped shared memory region
int* start_ptr;
start_ptr = static_cast<int*>(region.get_address());
// Write data into the buffer
int* write_ptr = start_ptr;
for(int i= 0; i<10; i++) {
cout << "Write data: " << i << endl;
memcpy(write_ptr, &i, sizeof(int));
write_ptr++;
}
// Read data from the buffer
int* read_ptr = start_ptr;
int* data;
for(int i= 0; i<10; i++) {
memcpy(data, read_ptr, sizeof(int));
cout << "Read data: " << *data << endl;
read_ptr++;
}
shared_memory_object::remove("MyName");
return 0;
}
当我运行它,它写入数据确定,但段错误在读取循环第一memcpy
。 gdb说以下内容:
程序接收到的信号EXC_BAD_ACCESS,无法访问内存。 原因:KERN_INVALID_ADDRESS在地址:0x0000000000000000 0x00007fffffe007c5在__memcpy()
(GDB)其中
#0 0x00007fffffe007c5在__memcpy() #1 0x0000000100000e45在主(的argc = 1,的argv = 0x7fff5fbff9d0)在试.cpp:36
功能非常简单,我不知道我错过了什么。任何帮助都感激不尽。
(脸红),这让我感觉很浓密!我似乎患有TIQL(暂时的智商损失)(我希望它是暂时的)。 谢谢! – recipriversexclusion 2010-03-03 21:21:37