Dereferencing type-punned pointer will break strict-aliasing rules

后端 未结 7 1459
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 01:05

I used the following piece of code to read data from files as part of a larger program.

double data_read(FILE *stream,int code) {
        char data[8];
              


        
7条回答
  •  离开以前
    2020-12-01 01:09

    This doc summarizes the situation: http://dbp-consulting.com/tutorials/StrictAliasing.html

    There are several different solutions there, but the most portable/safe one is to use memcpy(). (The function calls may be optimized out, so it's not as inefficient as it appears.) For example, replace this:

    return *(short*)data;
    

    With this:

    short temp;
    memcpy(&temp, data, sizeof(temp));
    return temp;
    

提交回复
热议问题