Reputation: 3127
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
Upvotes: 3
Views: 3455
Reputation: 54591
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.
Upvotes: 5
Reputation: 229184
mprotect() changes protection for the calling process's memory page(s) containing any part of the address range in the interval [addr, addr+len-1]. addr must be aligned to a page boundary
The last part here is important. malloc might not give you page aligned memory just because you request the size of a page, so you either have to allocate a suitable chunk of memory and align it, or allocate page aligned memory using e.g. posix_memalign()
You should also inspect errno if mprotect() fails, as to learn more about why it fails.
Upvotes: 5