Search code examples
cstructpaddingcalloc

C struct padding on initialization


I have a struct such as

typedef struct
{
    int a;  // Let's say this ends up being 4 bytes
    int b;  // 4 bytes
    char text[10]; // 10 bytes
} blah_t;

static blah_t myvar;
  1. Suppose the sum of fields’ sizes is 18 bytes in blah_t, but sizeof(blah_t) is 20 due to padding.
  2. The myvar is static, therefore it will be zero initialized.

Question:

  1. Are padding bytes 19 and 20 guaranteed to be 0 for a static variable? If not, I would need to do memset(&myvar, 0, sizeof(blah_t)) for any memcmp of the struct to be valid – even for a static variable.
  2. What about calloc(1, sizeof(blah_t))? Are bytes 19 and 20 guaranteed to be zero? I believe this is the case.

Solution

  • From ISO C99 standard: "When a value is stored in an object of structure or union type, including in a member object, the bytes of the object representation that correspond to any padding bytes take unspecified values."

    Looking further, this appears to discuss some additional issues: Comparing structures in C vs C++

    EDIT: not a duplicate of this question per se, but many common issues with detailed responses.