I have a very simple class that opens a file and creates a memory mapped file.
The region is mapped to the member variable called data_ which is defined as unsigned char* data_;
The memory map part looks like this:
// Create memory mapped file
unsigned char* data_ = (unsigned char*)mmap(NULL, 1024,
PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0);
if (block_data_ == MAP_FAILED) {
throw Exception(std::string("mmap: ") + strerror(errno));
}
Now I can read and write to the file by simply writing to the data_ variable (up to the size 1024.
But, the intention is not to do it this way. I have a function that returns me a pointer to data_.
When I simply create the block it works fine all the way up until I try to write to the data OUTSIDE of the class. That’s when I get a SIGSEGV.
How do I get around that?
I am not fully sure what you mean that you have done so far. In the code you posted, it appears as if you assign the return-value of
mmapto a local variabledata_instead of the member-variabledata_. Is this just the currently “working” version (that isn’t intended to use the member-variable), or is it an error?Are you sure you want to return a pointer to
data_? Isn’t itdata_itself that you want to return? Returning a pointer todata_sounds like something you might do if you want to change what it points to, but ifdata_already points to the mmapped area, doing that sounds wrong.Using the mmapped memory outside of the class should be no different from using it inside the class, so it sounds to me like you might have done something wrong either when assigning or returning the member-variable
data_.In the code you posted, you also check
block_datainstead ofdata_for error.