How to cast sockaddr_storage and avoid breaking strict-aliasing rules

后端 未结 4 954
情书的邮戳
情书的邮戳 2020-12-12 22:57

I\'m using Beej\'s Guide to Networking and came across an aliasing issue. He proposes a function to return either the IPv4 or IPv6 address of a particular struct:



        
4条回答
  •  独厮守ぢ
    2020-12-12 23:29

    I tend to do this to get GCC do the right thing with type-punning, which is explicitly allowed with unions

    I am pretty sure this (mis)use of union will not work (or only by accident) with GCC:

    short type_pun2 (int i, int *pi, short *ps) {
        *pi = i;
        return *ps;
    }
    
    union U {
        int i;
        short s;
    };
    
    short type_pun (int i) {
        U u;
        return type_pun2 (i, &u.i, &u.s);
    }
    

    The correct way to do that is with memcpy, not union.

提交回复
热议问题