Is it guaranteed that memset will zero out the pad

2019-04-05 06:08发布

问题:

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 like:

struct MyStruct
{
    unsigned char   member1;
    unsigned int    member2;
    char        member3;
    unsigned char   member4;
    float       member5;    
};

struct MyStruct ms;

memset(&ms, 0, sizeof( struct MyStruct));

回答1:

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.



回答2:

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));


回答3:

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.



标签: c gcc memset