cast from sockaddr * to sockaddr_in * increases required alignment

后端 未结 3 1741
情书的邮戳
情书的邮戳 2021-01-05 13:53

The compiler produces this warning when I\'m working with some code which looks like -

....

for(p = res; p != NULL; p = p->ai_next) {
    void *addr;
           


        
3条回答
  •  轮回少年
    2021-01-05 14:33

    Well -Weverything enables quite a lot of warnings some of them are known to throw unwanted warnings.

    Here your code fires the cast-align warning, that says explicitely

    cast from ... to ... increases required alignment from ... to ...

    And it is the case here because the alignement for struct addr is only 2 whereas it is 4 for struct addr_in.

    But you (and the programmer for getaddrinfo...) know that the pointer p->ai_addr already points to an actual struct addr_in, so the cast is valid.

    You can either:

    • let the warning fire and ignore it - after all it is just a warning...
    • silence it with -Wno-cast-align after -Weverything

    I must admit that I seldom use -Weverything for that reason, and only use -Wall


    Alternatively, if you know that you only use CLang, you can use pragmas to explicetely turn the warning only on those lines:

    for(p = res; p != NULL; p = p->ai_next) {
        void *addr;
        std::string ipVer = "IPv0";
    
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wcast-align"
    
        if(p->ai_family == AF_INET) {
            ipVer                    = "IPv4";
            struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
            addr                     = &(ipv4->sin_addr);
        }
    
        else {
            ipVer                     = "IPv6";
            struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
            addr                      = &(ipv6->sin6_addr);
        }
    #pragma clang diagnostic pop
    
    ....
    }
    

提交回复
热议问题