I got structure:
typedef struct
{
int a;
int b;
int c;
}Z;
code:
int main()
{
Z *a = (Z*)malloc(sizeof(Z)*8);
Z *b = (Z*)malloc(sizeof(Z)*8);
printf("%lu\n", sizeof(Z));
printf("%p %p\n", b, a);
printf("%lu\n", b - a);
}
output:
12
0x89a080 0x89a010
12297829382473034420
Why value in last line is so huge? Real address difference is 0x70 (16 bytes of heap allocation header plus 12*8 bytes of elements of array a), so from pointer's arithmetic I would expect value 0x70/12=9.(3) or 9 casted to integer. I know that substracted pointers don't point on the same arrays but I expected more reasonable result which would give me clue how memory map looks like. It was compiled on 64b Ubuntu and gcc 4.8.2.
assembly:
.file "aa.c"
.section .rodata
.LC0:
.string "%lu\n"
.LC1:
.string "%p %p\n"
.text
.globl main
.type main, @function
main:
.LFB2:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl $96, %edi
call malloc
movq %rax, -16(%rbp)
movl $96, %edi
call malloc
movq %rax, -8(%rbp)
movl $12, %esi
movl $.LC0, %edi
movl $0, %eax
call printf
movq -16(%rbp), %rdx
movq -8(%rbp), %rax
movq %rax, %rsi
movl $.LC1, %edi
movl $0, %eax
call printf
movq -8(%rbp), %rdx
movq -16(%rbp), %rax
subq %rax, %rdx
movq %rdx, %rax
sarq $2, %rax
movq %rax, %rdx
movabsq $-6148914691236517205, %rax
imulq %rdx, %rax
movq %rax, %rsi
movl $.LC0, %edi
movl $0, %eax
call printf
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE2:
.size main, .-main
.ident "GCC: (Ubuntu 4.8.2-19ubuntu1) 4.8.2"
.section .note.GNU-stack,"",@progbits