mprotect - how aligning to multiple of pagesize works?

Posted by user299988 on Stack Overflow See other posts from Stack Overflow or by user299988
Published on 2010-04-08T15:20:49Z Indexed on 2010/04/08 15:23 UTC
Read the original article Hit count: 349

Filed under:
|

Hi,

I am not understanding the 'aligning allocated memory' part from the mprotect usage.

I am referring to the code example given on http://linux.die.net/man/2/mprotect

char *p;
char c;
/* Allocate a buffer; it will have the default
   protection of PROT_READ|PROT_WRITE. */
p = malloc(1024+PAGESIZE-1);
if (!p) {
    perror("Couldn't malloc(1024)");
    exit(errno);
}
/* Align to a multiple of PAGESIZE, assumed to be a power of two */
p = (char *)(((int) p + PAGESIZE-1) & ~(PAGESIZE-1));
c = p[666];         /* Read; ok */
p[666] = 42;        /* Write; ok */
/* Mark the buffer read-only. */
if (mprotect(p, 1024, PROT_READ)) {
    perror("Couldn't mprotect");
    exit(errno);
}

For my understanding, I tried using a PAGESIZE of 16, and 0010 as address of p. I ended up getting 0001 as the result of (((int) p + PAGESIZE-1) & ~(PAGESIZE-1)).

Could you please clarify how this whole 'alignment' works?

Thanks,

© Stack Overflow or respective owner

Related posts about linux

Related posts about memory-management