News for hackers. Stuff that matters.
Re:The Lost Art of Structure Packing (2018) by bregma on Monday April 27, 2020 @12:07PM (#22997138)
If you rely on code containing undefined behaviour you're in for a world of butthurt sooner rather than later.

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?

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.

Re:The Lost Art of Structure Packing (2018) by nly on Monday April 27, 2020 @07:47PM (#23001618)
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.
Re:The Lost Art of Structure Packing (2018) by Asooka on Monday April 27, 2020 @01:14PM (#22997760)
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?
Re:The Lost Art of Structure Packing (2018) by saagarjha on Monday April 27, 2020 @09:29PM (#23002327)
Not stupid–pointer aliasing using a cast is undefined if the types do not match, unless the type you are converting to is a void * , char * , or unsigned char *.