Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

memset

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?

like image 289
Cornstalks Avatar asked Dec 25 '22 07:12

Cornstalks


1 Answers

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.

like image 50
tmyklebu Avatar answered Jan 19 '23 00:01

tmyklebu