Treat Undefined binary code reading behavior as different types

Asked

Viewed 24 times

1

They say that this inline function code has "Undefined behavior", either by binary codes of the same meaning in float and different in other types, or because the order of storage and use of the data can change with optimization and also change the results, etc.

union DWord {
    char32_t c ;
    signed __int32 si ;
    unsigned __int32 ui ;
    float f ;
} ;

inline int FloatToInt32( float f ){
    DWord dw ;
    dw.f = f ;
    return dw.si ;
}

Is this really an inappropriate way to implement binary code readings meaning values of various types? There is an officially accepted way to implement Union (or struct/class) Dword so that no performance losses occur and fix undefined behavior where Dword is used?

One more thing. Is there a standardized way to identify Ubs and repair them? Is there any source that says that behaviors are undefined and that alternative codes have defined behaviors?

  • 1

    It’s probably best you break down on multiple issues. As for detecting Undefined behavior, the Clang compiler has some "sanitizers" and one of them is precisely detecting Undefined behavior. Just compile for example how clang input.c -fsanitize=undefined

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.