cmemorymallocmprotect

Protecting allocated memory


I need to allocate dynamically some portions of memory, each with some protection - either RW or RX.

I tried to allocate memory by malloc, but mprotect always returns -1 Invalid argument.

My sample code:

void *x = malloc(getpagesize());
mprotect(x, getpagesize(), PROT_READ); // returns -1, it;s sample, so only R, not RW or RX

Solution

  • If you want to allocate a page of memory, the correct choice is probably to use mmap()

    void *x = mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
    

    Note that since you pass the permissions into the call, you really don't need to use mprotect() afterward. You can use it, however, to change the permissions later, of course, like if you want to load some data into the page before making it read only. You can later free it using munmap().

    Since this is an anonymous map, no backing file is used, so it behaves much like malloc() would in that sense.