Search code examples
cnestedstructurepack

C : Incorrect sizeof calculation of nested structure


I have issue with calculating size of nested structures in C. I am using attribute pack to not allow padding.

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct __attribute__((packed)) {
    uint32_t x;            // 4bytes
    uint32_t y;            // 4bytes
} bar_t;                  // total 8bytes

typedef struct __attribute__((packed)) {
    uint8_t a;               // 1bytes
    uint16_t b;              // 2bytes
    uint8_t c;               // 1bytes
    uint8_t d;               // 1bytes
    uint8_t e;               // 1bytes
    uint8_t f;               // 1bytes
    uint8_t g;               // 1bytes
    uint32_t h;              // 4bytes
    bar_t bar[0];            // 8bytes
} foo_t;                 //total 20bytes = 0x14

int main() {
    foo_t *foo = malloc(sizeof(foo_t));
    printf("sizeof foo 0x%lX  sizeof foo_t 0x%lX  sizeof bar_t 0x%lX\n", \
            sizeof(foo), sizeof(foo_t), sizeof(bar_t));
    return 0;
}

output:

sizeof foo 0x8  sizeof foo_t 0xC  sizeof bar_t 0x8

I expect result to be

sizeof foo 0x14  sizeof foo_t 0x14  sizeof bar_t 0x8

What is wrong here?


Solution

  • A zero length array doesn't take up any space. It's effectively just a pointer to the end of the object. You have to allocate extra space if you have more than zero entries.

    And foo is a pointer. I don't know why you'd expect a pointer to be 20 bytes, but pointers are clearly 8 bytes on your platform.