Ayende Rahien
Ayende Rahien

Reputation: 22956

SIGSEGV when calling mmap twice

I'm trying to run the following program on Ubuntu, but it crashes with segmentation fault.

What I'm trying to do is call mmap twice:

p1 = mmap(null, size: 16 * 4k, offset: 0);
p2 = mmap(p1+(16*4K), 136 * 4k , offset: 16 * 4k);

Basically, trying to create two consecutive memory regions mirroring two consecutive regions in a file. It is okay if the 2nd mmap would fail, but I would like to understand why it is causing a segmentation fault.

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

int main()
{
    int fd, ret;
    void* p1;
    void* p2;
    unlink ("test.file");// don't care if it doesn't exists

    fd = open("test.file", O_RDWR | O_CREAT | O_SYNC, ALLPERMS);

    if(fd == -1)
        return errno;

    ret = ftruncate(fd, 4096*16);
    if(ret != 0)
        return errno;

    p1 = mmap(NULL, 4096*16, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if(p1 == (void*)-1)
        return errno;

    ret = ftruncate(fd, 4096*150);
    if(ret != 0)
        return errno;

    // dies here!
    p2 = mmap(p1 + (4096*16), 4096*(150-16), PROT_READ | PROT_WRITE, MAP_SHARED |MAP_FIXED, fd, 4096*16);
    if(p2 == (void*)-1)
        return errno;


    return 0;
}

Upvotes: 0

Views: 727

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136208

It may allocate guard pages before and after your mapping to prevent from overflowing your mapping, they are supposed to segfault on read and write. Another option is that you hit the guard page under the stack. Check pmap output after the first mmap to be sure.

Try using mremap instead.

Upvotes: 3

Related Questions