Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When is memset to 0 nonportable?

From this comment in GCC bug #53119:

In C, {0} is the universal zero initializer equivalent to C++’s {} (the latter being invalid in C). It is necessary to use whenever you want a zero-initialized object of a complete but conceptually-opaque or implementation-defined type. The classic example in the C standard library is mbstate_t:

mbstate_t state = { 0 }; /* correctly zero-initialized */

versus the common but nonportable:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

mbstate_t state;
memset(&state, 0, sizeof state);

It strikes me as odd that the latter version could be unportable (even for implementation-defined types, the compiler has to know the size). What is the issue here and when is a memset(x, 0, sizeof x) unportable?

>Solution :

memset(p, 0, n) sets to all-bits 0.
An initializer of { 0 } sets to the value 0.
On just about any machine you’ve ever heard of, the two concepts are equivalent.

However, there have been machines where the floating-point value 0.0 was not represented by a bit pattern of all-bits-0. And there have been machines where a null pointer was not represented by a bit pattern of all-bits-0, either. On those machines, an initializer of { 0 } would always get you the zero initialization you wanted, while memset might not.

See also question 7.31 and question 5.17 in the C FAQ list.


Postscript: It’s not clear to me why mbstate_t would be a "classic example" of this issue, though.


P.P.S. One other difference, as pointed out by @ryker in a now-deleted answer: memset will set any "holes" in a padded structure to 0, while setting that structure to { 0 } might not.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading