Search code examples
c++mmap

Bus error with mmap memory region


In the following simple program:

# include <sys/mman.h>
# include <fcntl.h>
# include <cstdlib>

# include <cassert>

struct rgn_desc
{
  size_t end_;
  char data[];
};

int main(int argc, const char *argv[])
{
  int fd = open("foo.mm", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0700);

  assert(fd != -1);

  void * ptr = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
                    MAP_SHARED | MAP_POPULATE, fd, 0);

  assert(ptr != (void*) -1);

  rgn_desc * rgn_ptr = (rgn_desc*) ptr;
  rgn_ptr->end_ = 0; // <-- bus error
}

Basically, I want to manage a simple mmaped arena allocator and store as first part of the mapping the bytes that I have allocated. So, when I recover from a file, I get how many bytes were allocated.

However, the last line is giving me a bus error. Could someone explain why, and if possible, to suggest to me a way for avoiding it. I am running Linux on a 32 bits pentium and using clang++ compiler


Solution

  • According to the doc, a sig bus can trigger if:

    SIGBUS
        Attempted access to a portion of the buffer that does not
        correspond to the file (for example, beyond the end of the
        file, including the case where another process has truncated
        the file).
    

    In your snipped your file size don't match with your mmap() size (0, 4096), so you could use ftruncate() to increase the size of your file.

    ftruncate(fd, 4096);