C struct padding on initialization

c, calloc, padding, struct

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.

Problem

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; ``` - Suppose the sum of fields’ sizes is 18 bytes in `blah_t`, but `sizeof(blah_t)` is 20 due to padding. - The `myvar` is static, therefore it will be zero initialized. Question: - 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. - What about `calloc(1, sizeof(blah_t))`? Are bytes 19 and 20 guaranteed to be zero? I believe this is the case.

Original source

Related problems