4 ms·
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 byt
by bregma 7y ago
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?
- gambiting 7y agoI 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.
- saagarjha 7y agoYeah, this is technically undefined.
- nly 7y agoThis 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.
- Asooka 7y agoYou 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.
- saagarjha 7y ago> Their contents are undefined No, their contents has an unspecified value.
- RealityVoid 7y agoOk, this will sound stupid then, but is pointer aliasing using casts undefined?
- saagarjha 7y agoNot 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 *.