Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mmap invalid argument error

Tags:

c

linux

This is the first time I use mmap system call. I am getting invalid argument error and I do not understand why , obviously I missing something Please help me, thank you

#include <stdio.h>
#include <sys/mman.h>


int main() {

    long pageSize = getpagesize () ; 

    size_t length = 4096 ;


    int * map = (int * ) mmap ( 0 , length , PROT_READ | PROT_WRITE , MAP_ANONYMOUS , 0 , 0 ) ; 
        if ( map == MAP_FAILED ) {

            perror ( " error mapping " ) ;

        }

    return 0 ;
}
like image 501
krl Avatar asked Aug 09 '26 17:08

krl


2 Answers

You need to specify at least one of MAP_PRIVATE or MAP_SHARED in the flags. Also, as the other answer says, you should have -1 as the file descriptor for portability, but that's not where your problem is (since you tagged this question with linux and linux ignores the file descriptor for anon mappings).

like image 169
Art Avatar answered Aug 12 '26 09:08

Art


You are passing 0 as the file descriptor. Anonymous mappings should always use -1 as the file descriptor, since they are not backed by a file. Also, as the other answer says, MAP_ANONYMOUS should be complemented by either MAP_PRIVATE or MAP_SHARED.

The correct way to call it would be:

int *map = mmap(0, length, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);

Note that the cast is not necessary since mmap returns void *.

like image 33
Blagovest Buyukliev Avatar answered Aug 12 '26 08:08

Blagovest Buyukliev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!