Search code examples
cmemset

Is memset(&obj, 0, sizeof obj) less portable than initializing with {0}?


I recently ran into GCC's bug that prevents initializing some things with {0}. In that bug report, the person reporting it says:

The classic example in the C standard library is mbstate_t:

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

versus the common but nonportable:

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

While I prefer and try to use {0} to initialize something to zero, I have used, and have seen others use, the memset version to set something to zero. I haven't run into any portability issues in the past.

Question: Is using memset here really nonportable? If so, in what circumstances would it be nonportable?


Solution

  • Bitwise zero isn't guaranteed to be (T)0 for floating-point and pointer types. So if you memset one of those to zero, you're getting something that's at best implementation-defined.

    This question lists a few machines where the null pointer wasn't bitwise zero.

    I believe Cray made a few examples of machines where bitwise zero didn't make your floating-point number zero.