3 ms·
Yeah, my bad. I missed the point of the example (ie that the size argument might be too small). I assumed the point was memset writing to padding bytes. It is
by cygx 7y ago
Yeah, my bad. I missed the point of the example (ie that the size argument might be too small). I assumed the point was memset writing to padding bytes.
It is indeed true that y might not get zeroed in principle (though I doubt that'll happen in practice for this particular example as padding gets introduced to maintain alignment, and alignment factors a type's size, which is 1 in case of char).
A better example would be
struct boxed_value {
uint16_t flags;
double value;
};
struct boxed_value v;
memset(&v, 0, sizeof (uint16_t) + sizeof (double));
That's of course a braindead way to write it instead of the more convenient
memset(&v, 0, sizeof v);
That said, neither case will invoke undefined behaviour.
- aw1621107 7y agoI'm mildly surprised that wouldn't invoke undefined behavior if there was padding between the fields of the struct due to writing over only part of the second field, but then again I'm not as intimately familiar with the C standard as I should be.