MetallicPriest
MetallicPriest

Reputation: 30765

Why is mmap not working here

I get segmentation fault when I run the following piece of code...

int * x = mmap( 0, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE, 0, 0 );

x[0] = 42; // <--- Segmentation fault happens due to this

What is wrong here?

Upvotes: 1

Views: 8152

Answers (4)

And you should always check that the result of mmap is not MAP_FAILED (that is, (void *) -1) and use errno to get the error code in that case.

Your mmap could fail (e.g. because of resource limits set with setrlimit, or because the swap space is full).

Upvotes: 0

SoapBox
SoapBox

Reputation: 20609

You've specified the incorrect flags and file descriptor. It looks like what you want is an anonymous (not backed by a file) mapping. If that's the case, the correct call would be:

x = mmap(0, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);

You need to use the MAP_ANONYMOUS flag to tell Linux there is no file. And you should pass -1 for the file descriptor, not 0.

Upvotes: 9

maverik
maverik

Reputation: 5586

man mmap says:

On success, mmap() returns a pointer to the mapped area. On error, the value MAP_FAILED (that is, (void *) -1) is returned, and errno is set appropriately

Check, whether x == MAP_FAILED or not. May be this is the case.

Upvotes: 1

MetallicPriest
MetallicPriest

Reputation: 30765

OK, I got it. I forgot to place MAP_ANONYMOUS, so it should had been like this...

int * x = mmap( 0, 4096, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 
  0, 0 );

Its working this way.

Upvotes: 1

Related Questions