2

I'm trying to use POSIX shared memory on a Linux system. But when I try to copy data to it, I get a bus error. Here's the code:

#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

void main ()
{
    char *s = "a";
    //<!--make file descripter-->
    int fd = shm_open (s, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
    if (fd == -1)
    {
        perror ("shm open:");
        printf ("error\n");
        shm_unlink (s);
        exit (1);
    }

    //<!--memory allocation-->
    char *str = (char *)mmap (NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (str == MAP_FAILED)
    {
        perror ("mmap");
        exit (1);
    }

    *(str + 1) = 'a';   
    //<!--memory deallocation-->
    munmap (str, 10);
    //<!--unlink shared memory-->
    shm_unlink (s);
}

What causes it to crash?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • It is not clear where the error is. Can you paste the error? – Felipe Tonello Aug 20 '15 at 11:48
  • 1
    `main()` must return `int` - I'm guessing you're not compiling with `gcc -Wall`? Definitely turn up your diagnostic reporting - sooner rather than later! (it will probably catch you assigning a string literal to `s`, too) – Toby Speight Aug 20 '15 at 12:38
  • 1
    Also, don't cast the result of `mmap()` - for the same reason that we don't cast the result of `malloc()`: [Do I cast the result of malloc?](https://stackoverflow.com/q/605845/4850040). – Toby Speight Aug 20 '15 at 12:50

1 Answers1

4

You are accessing memory beyond the end of the file you mapped. You need to extend the size of the file to acquire the space. After shm_open(), add:

int size = 10; // bytes
int rc = ftruncate(fd, size);
if(rc==-1){ ...; exit(1); }
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
meuh
  • 11,500
  • 2
  • 29
  • 45