Sample code:
#include <assert.h>
struct S
{
unsigned char ch;
int i;
};
int main()
{
struct S s;
memset(&s, 0, sizeof s);
s.ch = 257;
assert( 0 == ((unsigned char *)&s)[1] );
}
Can the assertion fail?
The motivation for the question is whether a compiler on a little-endian system could decide to use a 4-byte store to implement s.ch = 257;
. Obviously nobody would ever write code like I did in my example, but something similar might realistically occur if ch
is assigned in various ways in a program which then goes on to use memcmp
to check for struct equality.
For example, if the code does --s.ch
instead of s.ch = 257
- can the compiler emit a word-size decrement instruction?
I don't think the discussion around DR 451 is relevant, as that only applies to uninitialized padding; however the memset
initializes all the padding to zero bytes.