Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 400
Ari Avatar asked Mar 09 '26 14:03

Ari


1 Answers

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.

like image 148
FatalError Avatar answered Mar 11 '26 04:03

FatalError



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!