Segfault when accessing mmaped memory on Cygwin

Thomas Koenig tkoenig@netcologne.de
Fri Jan 1 21:11:01 GMT 2021


Hi,

when trying out uf a certain shared memory allocator would
work on Cygwin, I tried out the sample program below (which
works on Linunx, *BSD, AIX and Solaris) and got a suprising
falure with a segmentation fault at the line

   *i1 = 42;

mmap() had succeeded.

Is this a known issue, and would it be possible to work
around that?

Best regards

	Thomas

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

#define NAME "/random_namexxx"

int main()
{

   int fd;
   long pagesize;
   void *p1, *p2;
   volatile int *i1, *i2;
   size_t size1, size2;
   off_t offset;

   pagesize = sysconf (_SC_PAGE_SIZE);
   if (pagesize == -1)
     {
       perror ("sysconf failed");
       exit (EXIT_FAILURE);
     }

   fd = shm_open (NAME, O_CREAT | O_EXCL | O_RDWR,  S_IRUSR | S_IWUSR);
   if (fd == -1)
     {
       perror ("shm_open failed");
       exit (EXIT_FAILURE);
     }
   shm_unlink (NAME);

   offset = 0;
   size1 = pagesize;
   p1 = mmap (NULL, size1, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
   if (p1 == MAP_FAILED)
     {
       perror ("mmap 1 failed");
       exit (EXIT_FAILURE);
     }
   printf ("p1 = %p\n", p1);
   ftruncate (fd, size1);
   i1 = p1;
   *i1 = 42;
   size2 = 2 * size1;
   p2 = mmap (NULL, size2, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
   if (p2 == MAP_FAILED)
     {
       perror ("mmap 1 failed");
       exit (EXIT_FAILURE);
     }
   printf ("p2 = %p\n", p2);
   i2 = p2;
   ftruncate (fd, size2);
   printf ("%d\n", *i2);
   return 0;
}


More information about the Cygwin mailing list