2 ms·
Is all-bits-zero really "safe"? Sure, sometimes it is, but the safest approach is ensure that you've assigned a valid value to any object before you access that
by _kst_ 11y ago
Is all-bits-zero really "safe"? Sure, sometimes it is, but the safest approach is ensure that you've assigned a valid value to any object before you access that value.
If you fail to do that, pre-zeroing might just give you consistent incorrect behavior. It can also inhibit a compiler's ability to detect that you're accessing an uninitialized object. The compiler has no way of knowing whether that zero-initialization was setting it to a meaningful zero value, or just "clearing" it for safety.
- pjmlp 11y agoSafe in the sense of being initialized to a known value instead of random data. Other than that, you're right.
- nhaehnle 11y agoIt is fairly easy to develop software in such a way that the correctly initialized version of most structures is mostly zero. If you get in the habit of designing your code that way, calloc is clearly superior: you get much faster initialization of your structures (because of SSE or equivalent optimizations for memset) and your code is more maintainable (because extending a structure with a field where a zero value implies unchanged behaviour will just work without changing all the places where the structure is initialized).