cargumentsmprotect

mprotect() Invalid argument in C


I want to allocate 4096 Bytes with posix_memalign in the array "page", and then protect it with PROT_NONE via mprotect(). The allocation seems to work, but protect() returns 1 instead of 0. The given error code is "Invalid argument".

I think it's only a small mistake, I am not able to detect. Thanks in advance for any help or suggestions.

uint8_t *page;
size_t page_size = 4096;
size_t alignment = 8;

int main(int argc, char* argv[]) {
    if (posix_memalign((void **) &page, alignment, page_size) != 0) perror("Allocation failed!");
    if (mprotect(page, page_size, PROT_NONE) != 0) perror("mprotect() failed!");
}

Solution

  • Try the way in the code below ... and read better the man-pages:

    man -S3 posix_memalign

    man -S2 mprotect

    #include <stdlib.h>
    #include <stdio.h>
    #include <errno.h>
    #include <sys/mman.h>
    #include <stdint.h>
    #include <inttypes.h>
    #include <unistd.h>
    
    uint8_t *page=NULL;
    size_t page_size;
    size_t alignment = 8;
    
    int main(int argc, char* argv[]) {
        int blen;
    
        // page_size=getpagesize();
        page_size = sysconf(_SC_PAGE_SIZE);
    
        blen=page_size * 2;
    
        if (posix_memalign((void **) &page, page_size, blen) != 0)
            perror("Allocation failed!");
    
        if (mprotect(page, page_size, PROT_READ | PROT_WRITE) != 0)
            perror("mprotect() failed!");
    }