For my curiosity, I wrote a program that was supposed to show every byte of my structure. Here is the code:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <limits.h> #define MAX_INT 2147483647 #define MAX_LONG 9223372036854775807 typedef struct _serialize_test{ char a; unsigned int b; char ab; unsigned long long int c; }serialize_test_t; int main(int argc, char**argv){ serialize_test_t *t; t = malloc(sizeof(serialize_test_t)); t->a = 'A'; t->ab = 'N'; t->b = MAX_INT; t->c = MAX_LONG; printf("%x %x %x %x %d %d\n", t->a, t->b, t->ab, t->c, sizeof(serialize_test_t), sizeof(unsigned long long int)); char *ptr = (char *)t; int i; for (i=0; i < sizeof(serialize_test_t) - 1; i++){ printf("%x = %x\n", ptr + i, *(ptr + i)); } return 0; }
and here is the result:
41 7fffffff 4e ffffffff 24 8 26b2010 = 41 26b2011 = 0 26b2012 = 0 26b2013 = 0 26b2014 = ffffffff 26b2015 = ffffffff 26b2016 = ffffffff 26b2017 = 7f 26b2018 = 4e 26b2019 = 0 26b201a = 0 26b201b = 0 26b201c = 0 26b201d = 0 26b201e = 0 26b201f = 0 26b2020 = ffffffff 26b2021 = ffffffff 26b2022 = ffffffff 26b2023 = ffffffff 26b2024 = ffffffff 26b2025 = ffffffff 26b2026 = ffffffff
And here is the question: if sizeof(long long int) is 8 , then why sizeof(serialize_test_t) is 24 instead of 32 - I always thought that the size of the structure is rounded to the largest type and multiplied by the number of fields, for example, here: 8 (bytes ) * 4 (fields) = 32 (bytes)) - by default, without pragma pack directives?
Also, when I discard this structure in char * , I see in the output that the offset between the values ββin memory is not 8 bytes. Could you give me the key? Or maybe it's just a compiler optimization?
Josip source share