4 ms·
And I believe that's wrong. Memset copies values to bytes, regardless if they are padding or not. You just can't rely on padding bytes keeping that value. In pa
by cygx 7y ago
And I believe that's wrong. Memset copies values to bytes, regardless if they are padding or not. You just can't rely on padding bytes keeping that value. In particular, writing to a member may fill padding with arbitrary garbage (though the standard goes beyond that, ie you shouldn't rely on padding values ever).
- aw1621107 7y agoWhy would it be wrong? If there's 3 bytes of padding between x and y, then writing 2 bytes of 0s to &a would zero out x and the first padding byte, but would not zero y.
- cygx 7y agoYeah, 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.
- fhars 7y agoNo, it is true. The point is that the code in the example is incompetently written, if you want to zero out a struct foo, you should memset sizeof(struct foo), not /* manually calculate what you think the size of foo will turn out to be */ ...
- acqq 7y ago> if you want to zero out a struct foo, you should memset sizeof(struct foo), not /* manually calculate what you think the size of foo will turn out to be Exactly. Any other approach than using sizeof(struct foo) is definitely wrong. What author tried to do with sizeof(char) * 2 never worked in C except by accident, and it was so even in 1975 when no modern standard existed and "undefined" wasn't misused.
- tumult 7y agoIt's fine to write this if you know it's OK. There's nothing inherently wrong with it, as far as C99 is concerned. Of course, if you want to zero the entire region of the struct, sizeof(MyGuy) is better. (Though, it may write to useless padding bytes that never get read... but, it might not be useless if you're a kernel and don't want to leak information via uninitialized padding!)
- deleted 7y ago[deleted]