4 ms·
> It might make sense to use something like memcmp() on structs to assert that they are exactly the same No, actually, it doesn't make sense in general. Due t
by usrnm 7y ago
> It might make sense to use something like memcmp() on structs to assert that they are exactly the same
No, actually, it doesn't make sense in general. Due to padding, structs may have arbitrary meaningless bytes between the actual data fields, and memcmp will break on those. It works because structs are often filled with zeroes on initialization, but it isn't required or enforced in any way. I was burnt by this problem more than once, not really fun to debug
- Gibbon1 7y agoFun, create a struct on the stack. Set the elements individually. Padding is now filled with garbage. Any elements you forget to set will also be garbage. When you copy the struct the garbage goes with it. I've been burnt too.
- mjevans 7y agoYou've missed the 'functionally equal' check option; which covers cases like you're focusing on. To check if two differently created things happen to be equal, yes, you should prefer the function that checks exactly what matters exactly how it matters. As you rightly point out, the memcmp check would only work on either pre-zeroed memory (depends on environment and what you're doing) or actual literal copies of a specific struct.