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!");
}
mprotect
returns-1
, not1
. – Some programmer dudemprotect
specification says that "The implementation may require that addr be a multiple of the page size as returned bysysconf()
". And thatEINVAL
(the error you get) is for "Theaddr
argument is not a multiple of the page size as returned bysysconf()
" On your system, are you sure the page-size is 4k? – Some programmer duden = mprotect(page, page_size, PROT_NONE) != 0
does not do what you think it does. It first evaluatesmprotect(page, page_size, PROT_NONE) != 0
and then assign the boolean1
or0
result ton
. Try instead(n = mprotect(page, page_size, PROT_NONE)) != 0
. – Some programmer dude