3 ms·
I disagree with this author on both counts. 1. Zero filling is theoretically unnecessary, yes. But theory is not often reality. Zero filling is a defensive meas
by nerdile 7y ago
I disagree with this author on both counts.
1. Zero filling is theoretically unnecessary, yes. But theory is not often reality. Zero filling is a defensive measure that protects you from other code that makes unhealthy assumptions. Code external to yours may make assumptions about what lies in your padding, either by doing memcmp's, or adding new fields in a later version of the struct and intending it to be ABI compatible between modules. I'll prefer safe and evolvable code over your nitpick about how it's initialized, thank you very much.
2. Consider yourself lucky that you only use free() in your code. In more complex code bases, custom allocators are used. They do not always follow the same semantics as are dictated for free().
Maybe instead of saying "this perfectly valid thing drives me nuts", ask why people do it. It's not because they don't know better.
- iforgotpassword 7y ago> Code external to yours may make assumptions about what lies in your padding, either by doing memcmp's, or adding new fields in a later version of the struct and intending it to be ABI compatible between modules. The content of the padding between members can arbitrarily change during assignments of members, so code relying on the content of it is broken anyways. In the case of an extended struct both methods are equally broken if you don't recompile your module with the updated definition of the struct. Your memset will still have the old size of the struct as the third argument.
- hedora 7y agoIf you use: sizeof(struct_instance) the compiler will automatically update the size passed to memcpy. (I like passing the instance to sizeof and not the type, just in case the type of the thing being copied changes in a future version of the code.)
- iforgotpassword 7y agoThat is exactly what I said: > ...if you don't recompile your module with the updated definition of the struct... And once you recompiled, the C99 version with the pretty initializer is fixed as well, so there is no advantage in using memset regarding this.
- saagarjha 7y agoThe compiler may elide memset if it's not possible to access the value in a standards-defined way, so your defense might not actually be doing anything.