c - 在结构中包含更改 sizeof in_addr

标签 c

好的,我有一个包含 struct in_addr 元素的结构。 这应该使结构 addrlist_t 至少 12 字节大小 (8 + 4)。平台是amd64

#include <netinet/in.h> // struct in_addr
#include <stdio.h> // printf()
#include <netdb.h> // toggles size of struct addrlist_t

struct addrlist_t {
    struct addrlist_t *next;
    struct in_addr h_addr;
};

int main(int argc, char *argv[]) {
    printf("%zu + %zu = %zu\n",
        sizeof (struct addrlist_t *), sizeof (struct in_addr), 
        sizeof (struct addrlist_t)
    );
    return 0;
}

这是完全出乎意料的输出:

$cc main.c -o main -Wall -Wwrite-strings -pedantic -std=gnu99 -Wall -Werror
$./main
8 + 4 = 8

这似乎没有意义。组合大小应至少为 12,不能更小!

但是现在,当 #include <netdb.h> 被移除时,预期的输出出现:

$./main
8 + 4 = 16

-std=gnu99 被替换为 -std=c99 时,同样的事情会发生。

有人可以解释这种行为吗?

为了完整性:

$file main
main: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=709ab89d012d8b5a6ae7423fd80ce643288cba95, not stripped

编辑:格式/文字

最佳答案

这是因为您为 struct in_addr h_addr 取了一个不幸的名字成员(member)。

<netdb.h>在 glibc 中包含这个:

# define    h_addr  h_addr_list[0] /* Address, for backward compatibility.*/                       

运行 gcc -E main.c 以查看您的代码在预处理后的外观, 你的 struct addrlist_t 基本上变成了这样:

struct addrlist_t {
    struct addrlist_t *next;
    struct in_addr h_addr_list[0];
};

这与您的预期完全不同。

关于c - 在结构中包含更改 sizeof in_addr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28043087/

相关文章:

c - GCC 以相反的顺序编译 EEPROM 地址

c - 如何让一个子进程等待它的兄弟?

c - 为什么 execvp 或 exec* 系列函数之后的任何内容都不会被执行?

c - pthread_create 内存泄漏

复制多维数组 C

c - 它仍然崩溃,我哪里出错了?

无法在 C 中声明大小为 400000 的数组

c - 函数似乎没有修改数组

c - 为 ARM 编译 Kernel-aodv 时出错

c - C 与 Python/numpy 的数学表现较差