c - What is the difference in these stack and heap memory addresses? -
i making example stack , heap allocation on ubuntu 14.04 vm (linux 3.13.0-55-generic i686) , confused memory addresses heap allocations.
the below c code allocates 3 32-bit unsigned ints on stack , 3 allocation on heap of diminishing sizes, 32 bits, 16 bits , 8 bits.
in output below can see memory addresses 3 32 bit ints on stack 4 bits apart. uint32_t @ 0xbffd4818 , 4 addresses later @ 0xbffd481c uint32_t j. can see here each individual byte of memory addressable , each 4 byte memory block 4 memory addresses apart.
looking @ heap allocations though can see uint32_t i_ptr points 0x99ae008 , malloc requested 4 bytes of space, expect uint16_t j_ptr start @ 0x99ae00c starts @ 0x99ae018. third heap allocation uint8_t k_ptr starts 16 bytes after uint16_t i_ptr starts 16 bytes after uint32_t i_ptr.
- is default os setting each heap allocation 16 bytes apart?
- why happening irrelevant of size passed malloc?
- how can fit 4 bytes of information between 0x99ae008 , 0x99ae018?
c source:
#include <stdint.h> #include <stdlib.h> #include <stdio.h> int main () { register uint32_t ebp asm ("ebp"); printf("0x%x\n", ebp); register uint32_t esp asm ("esp"); printf("0x%x\n", esp); uint32_t i; printf("%p\n", &i); uint32_t j; printf("%p\n", &j); uint32_t k; printf("%p\n", &k); uint32_t *i_ptr = malloc(4); printf("%p\n", i_ptr); uint16_t *j_ptr = malloc(2); printf("%p\n", j_ptr); uint8_t *k_ptr = malloc(1); printf("%p\n", k_ptr); free(i_ptr); free(j_ptr); free(k_ptr); return 0; }
cli output:
$ gcc -o heap2 heap2.c $ ./heap2 0xbffd4838 // ebp 0xbffd4800 // esp 0xbffd4818 // uint32_t 0xbffd481c // uint32_t j 0xbffd4820 // uint32_t k 0x99ae008 // uint32_t i_ptr 0x99ae018 // uint16_t j_ptr 0x99ae028 // uint8_t k_ptr
malloc returns pointer of type void *
may casted pointer of other type. malloc provides alignment satisfies requirement of type.
usually malloc returns address aligned paragraph (in systems equal 16 bytes). , malloc allocates extents have minimal size of paragraph. if write example
char *p = malloc( 1 );
then in fact malloc reserves extent of 16 bytes.
Comments
Post a Comment