Cornstalks
Cornstalks

Reputation: 38228

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?

Upvotes: 4

Views: 623

Answers (3)

haccks
haccks

Reputation: 106092

Is using memset here really nonportable?

It depends.

If so, in what circumstances would it be nonportable?

Setting an integer to zero bits using memset always makes the integer zero.
Setting a floating-point number to zero bits using memset usually makes number zero, but this is not guaranteed-- it depends on how floating point numbers are stored.
The story is same for pointers; a pointer whose bits are set to be zero isn't necessary a NULL pointer.

Upvotes: 1

YePhIcK
YePhIcK

Reputation: 5866

"The use of memset for this purpose makes the assumption that a bit pattern of all zeros corresponds to a numeric value of zero or a pointer value of null. This is true for most types in most implementations of C, but is not a requirement of the ISO standard".

The above quote is taken from http://www.codepolice.org/c/memset.html (which was the first Google hit for "portability issues with memset")

Upvotes: 1

tmyklebu
tmyklebu

Reputation: 14215

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.

Upvotes: 8

Related Questions