c - mprotect on heap aligned memory works mysteriously -


so trying check if can change access rights on mmapped allocated memory using mprotect , wrote:

#include <stdio.h> #include <sys/mman.h> #include <malloc.h> #include <unistd.h>  void main() {         int pagesize;         pagesize = getpagesize();         void *p;         p = malloc(pagesize);         getchar();         int q = posix_memalign(&p, pagesize, pagesize);         getchar();         int = mprotect(p, pagesize, prot_read | prot_write | prot_exec);         getchar();         free(p); } 

now after each function using getchar analyze memory segment using cat /proc/<pid>/maps file , get: (only showing information regarding heap concern) after posix_memalign:

01776000-01798000 rw-p 00000000 00:00 0                                  [heap] 

after mprotect function:

01776000-01778000 rw-p 00000000 00:00 0                                  [heap] 01778000-01779000 rwxp 00000000 00:00 0                                  [heap] 01779000-01798000 rw-p 00000000 00:00 0                                  [heap] 

so if notice heap allocated before gets divided 3 parts after use mprotect , second part of heap gets access permissions gave in function. why division happens , why second region of divided heap gets permissions? note: have searched manpages , have found absolutely nothing regarding this.

you allocated 0x1000 bytes @ address p, 0x1778000 in example. when called mprotect these parameters, did indeed work wanted , marked 01778000-01779000 rwxp.

your question more aptly phrased as, why posix_memalign(3) seem allocate more space requested?

lets take @ man posix_memalign:

posix requires memory obtained posix_memalign() can freed using free(3).

but how free(3) know how bytes free? needs store somewhere outside page allocated. , how subsequent invocations of malloc(3) or friends know find freed blocks? these need stored somewhere too.

and no surprise heap allocator stores data structures uses manage heap on heap.

if want more low-level way allocate page, use mmap(2):

p = mmap(0, getpagesize(), prot_read|prot_write, map_private|map_anonymous, -1, 0); 

this memory managed you, when call munmap(2), mapping deleted notifying kernel directly. no recycling or management done in user space.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -