This is driving me wild with frustration. I am just trying to create a shared memory buffer class that uses in shared memory created through Boost.Interprocess where I can read/store data. I wrote the following to test the functionality
#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;
}
When I run this, it writes the data OK, but segfaults on the first memcpy
in the read loop. gdb says the following:
Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000 0x00007fffffe007c5 in __memcpy ()
(gdb) where
#0 0x00007fffffe007c5 in __memcpy () #1 0x0000000100000e45 in main (argc=1, argv=0x7fff5fbff9d0) at try.cpp:36
The functionality is so simple, I don't know what I'm missing. Any help will be much appreciated.