Do I have a gcc optimization bug or a C code problem?

前端 未结 9 2448
借酒劲吻你
借酒劲吻你 2021-02-06 00:57

Test the following code:

#include 
#include 
main()
{
    const char *yytext=\"0\";
    const float f=(float)atof(yytext);
    siz         


        
9条回答
  •  没有蜡笔的小新
    2021-02-06 01:45

    It is bad C code :-)

    The problematic part is that you access one object of type float by casting it to an integer pointer and dereferencing it.

    This breaks the aliasing rule. The compiler is free to assume that pointers to different types such as float or int don't overlap in memory. You've done exactly that.

    What the compiler sees is that you calculate something, store it in the float f and never access it anymore. Most likely the compiler has removed part of the code and the assignment has never happend.

    The dereferencing via your size_t pointer will in this case return some uninitialized garbage from the stack.

    You can do two things to work-around this:

    1. use a union with a float and a size_t member and do the casting via type punning. Not nice but works.

    2. use memcopy to copy the contents of f into your size_t. The compiler is smart enough to detect and optimize this case.

提交回复
热议问题