g123k
g123k

Reputation: 3874

Mmap problem -> segfault

I would like to share to use mmap. However it doesn't work, because I'm getting a segfault :

int fdL = open("/dev/zero", O_RDWR | O_CREAT);
int *ligneC = (int *) mmap(0, sizeof (int), PROT_READ | PROT_WRITE, MAP_SHARED, fdL, 0);

*ligneC = 0;

Where am I wrong ?

Upvotes: 0

Views: 1388

Answers (1)

Piotr Praszmo
Piotr Praszmo

Reputation: 18320

Your code works fine for me. Try adding some error checks to your code. You will know what is failing and why:

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

int main(int argc,char*argv[])
{
    int fdL = open("/dev/zero", O_RDWR | O_CREAT);

    if(fdL<0)
    {
        perror("open");
        exit(1);
    }

    int *ligneC = (int *) mmap(0, sizeof (int), PROT_READ | PROT_WRITE, MAP_SHARED, fdL, 0);

    if(ligneC==(int*)-1)
    {
        perror("mmap");
        exit(1);
    }

    *ligneC = 0;
    return 0;
}

Upvotes: 1

Related Questions