Is it guaranteed that memset will zero out the padding bits in a structure?

后端 未结 3 2371
独厮守ぢ
独厮守ぢ 2021-02-20 16:54

In general ,as per C standard is it guaranteed that memset() with 0 will zero out the padding bits in a C structure?

What about gcc?

For example , something lik

3条回答
  •  再見小時候
    2021-02-20 17:27

    If it matters, you're likely doing something unsafe and non-portable.

    Yes, the memset call will set any padding bits (or bytes) to 0 -- but there's no guarantee in the language that setting a float object to all-bits-zero will set it to 0.0. The same applies to pointers: all-bits-zero isn't guaranteed to be a null pointer. (In both cases, it happens to be true for most implementations.)

    The original ISO C90 or C99 standard didn't even guarantee that all-bits-zero is a valid representation of 0 for integer types; one of the post-C99 Technical Corrigenda added such a guarantee (for integer types only).

    For portability, if you want something to be zero, set it explicitly. You can also take advantage of the zero value initialization for static objects and for omitted members in initializers.

    A terminological nitpick: "padding bits" are part of the representation of integer types (and usually there are none of them). Padding between struct members is padding bytes.

提交回复
热议问题