Re:The Lost Art of Structure Packing (2018)
by gambiting on Monday April 27, 2020 @12:20PM
(#22997258)
I don't have the code in front of me, but something like
int hash=0;
for(int i=0;i<sizeof(obj);i++)
hash += hashing_method(reintepret_cast<char*>(&obj)+i);
return hash;
Basically hashing each byte of the memory containing the object, regardless of what the object itself represents.We can argue whether that's a smart thing to do or not, but I wasn't in charge of implementing it - it's a relic from a codebase that's more than a decade old at this point. It's a simple hashing method that works with most types, but obviously dies horrendously in a case like this.
This doesn't help you, because the contents of the padding bytes is not guaranteed to be anything in particular. Two structs containing identical field values can have different padding bytes. Reading the padding bytes is UB.
Just pack the struct and be done with it.
Re:The Lost Art of Structure Packing (2018)
by saagarjha on Monday April 27, 2020 @12:48PM
(#22997512)
Yeah, this is technically undefined.
You can trivially get at the padding bytes, just cast to char pointer. Their contents are undefined and there is absolutely no guarantee that they will remain constant, but they're there.
Generally you have several possibilities for how to escape this problem, but the simplest is to just add the padding and a static assert that the sizeof the struct is what you expect.
Re:The Lost Art of Structure Packing (2018)
by saagarjha on Monday April 27, 2020 @09:19PM
(#23002267)
> Their contents are undefined
No, their contents has an unspecified value.
Re:The Lost Art of Structure Packing (2018)
by RealityVoid on Monday April 27, 2020 @05:27PM
(#23000269)
Ok, this will sound stupid then, but is pointer aliasing using casts undefined?
There is no way in C++ to get at the padding bytes unless you're using undefined behaviour. How does the hash function work? Pointer aliasing using reinterpret_cast? Pointer aliasing using C-style casts? Typing punning through the old union switcheroo?