This article takes a look at a few different aspects of C structure
initialization. In particular, we’ll look at when it matters, the current state
of things in Clang and GCC, recommendations, and the ✨ future ✨.
A great article. For an optimized and/or secure system, it’s important to pay attention to these small details of how things look in memory.
However, I can’t believe I didn’t know about the pahole tool - I’ve been manually inserting those offset comments when optimizing…
I recently wrote an article about a similar topic - and one thing I wrote about is what unaligned accesses look like in memory and why they are bad or simply not allowed:
That’s some great data, thanks Noah! Sound conclusions too. I think in C it pays to be explicit.
A potentially useful technique to enable this practice: union with a byte array. In some scenarios (eg. serialisation) I’ve found this useful to have a convenient record based syntax as well as contiguous byte access so you don’t have to rely on implicit assumptions.
You can then avoid memcpy and use an initialiser instead:
union fooWithByteAccess f = {.bytes = {0}};
You still need to be very careful - reading and writing to a union using different members is called “type punning”, and if the members are different sizes, or you’re using C90, there are really nasty dragons. See here for some confusing clarifications - as always, trust but verify!