So we had a discussion about C++ at work today. It seems something I've done for years and seen in a million places is UB?! uint8_t* pSomeBlob; auto pHeader = reinterpret_cast<Header*>( pSomeBlob ); This is supposedly undefined behavior, is that true?
I believe the gotcha is that the compiler is allowed to reinterpret the variable however it wants. The only restriction is that if you reinterpret the same variable back to the original type, it must be the same as it was before. That’s been my understanding.
-
-
Also, UB isn’t always a no-no. If you’re using a certain compiler and you know what that compiler will do, then it’s perfectly fine. You may one day find s compiler that doesn’t do that. UB is only bad if you don’t know your platform/compiler.
-
If I’m not mistaken, the reason for the wording is more for int<->float, or int<->pointer, where the types aren’t exactly related. In practice, T1*<->T2* is chill and the compiler will do what you expect.
Keskustelun loppu
Uusi keskustelu -
-
-
Any idea why the initial code doesnt trigger any warnings with strict-aliasing or UBsan? It seems clang at least things it's perfectly legal: https://godbolt.org/z/DPcr2P
-
I’ve never used UBsan, so I can’t say for sure. But I don’t see anything related to it on the list of available checks. https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html …
Keskustelun loppu
Uusi keskustelu -
-
-
For one thing, it’s easy for this code to blatantly disrespect the alignment requirements of the target type. More than one budding binary file designer has been bitten hard when they were forced to port to e.g. ARM.
Kiitos. Käytämme tätä aikajanasi parantamiseen. KumoaKumoa
-
Lataaminen näyttää kestävän hetken.
Twitter saattaa olla ruuhkautunut tai ongelma on muuten hetkellinen. Yritä uudelleen tai käy Twitterin tilasivulla saadaksesi lisätietoja.