c++ - Why the Memory locations for two variables which is allocated dynamically are not consecutive? -
this question has answer here:
i use 2 variables in memory allocated dynamically, , print memory locations, not consecutive. why?
#include <stdio.h> #include <stdlib.h> int main() { int *a = malloc(sizeof(int)); int *b = malloc(sizeof(int)); printf("\n a=%p \t b=%p \n",a,b); }
the answers (in linux) are
1st time:
a=0x20a0010 b=0x20a0030
2nd time:
a=0x657010 b=0x657030
3rd time:
a=0x139e010 b=0x139e030
why exact difference between memory locations of a
, b
variables way in 1st, 2nd , 3rd times?
is related paging memory?
my processor 64 bit.
the gap between 2 consecutive allocations not related paging. allocations small reside in data segment. libc handles these internally - space outside sizeof int
bytes contains pointers previous , next block of data , size of allocation - after free
pointer , need figure out how memory deallocate.
additionally both of these pointers aligned 16-byte boundary. c11 7.22.3 says
the pointer returned if allocation succeeds suitably aligned may assigned a pointer type of object fundamental alignment requirement , used access such object or array of such objects in space allocated (until space explicitly deallocated).
thus though you're using them int
c standard requires pointer returned aligned data type - on implementation 16 bytes.
if allocate object large, glibc map entire pages using mmap
instead. alignment (on 64-bit computer) 16 bytes start of 4k page:
#include <stdio.h> #include <stdlib.h> int main() { int *a = malloc(12345678); int *b = malloc(12345678); printf("\n a=%p \t b=%p \n",a,b); }
when run
% ./a.out a=0x7fb65e7b7010 b=0x7fb65dbf0010
one can see mmap
calls strace ./a.out
- there among other system calls there are
mmap(null, 12349440, prot_read|prot_write, map_private|map_anonymous, -1, 0) = 0x7fb65e7b7000 mmap(null, 12349440, prot_read|prot_write, map_private|map_anonymous, -1, 0) = 0x7fb65dbf0000
as why addresses keep changing 1 execution - due address space layout randomization, or aslr - security mechanism makes harder evil crackers predictably exploit undefined behaviour in code.
p.s. if need dynamically allocate space 2 int
s @ consecutive addresses, allocate array.
Comments
Post a Comment