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

后端 未结 3 2287
独厮守ぢ
独厮守ぢ 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

    Yes, memset writes a 32 bit value into a contiguous region of memory of a given length starting at the given address. In your case, memset writes the region with (32bit value) 0.

    So if you do a memset of length sizeof (your_struct), you should be fine:

    memset(&ms, 0, sizeof(struct MyStruct));
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-20 17:34

    Perhaps worth noting that memset doesn't know anything about your struct (or array, or primitive, or any chunk of memory whatsoever that you happen to unleash it on), so even if it wanted to leave the padding bits intact, it wouldn't even know where they are.

    0 讨论(0)
提交回复
热议问题