c - 如何计算结构的大小?

标签 c linux struct

man unix(7)我发现了以下内容:

pathname: a UNIX domain socket can be bound to a null-terminated filesystem pathname using bind(2). When the address of a pathname socket is returned (by one of the system calls noted above), its length is

offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1

struct sockaddr_un 定义为

struct sockaddr_un {
    sa_family_t sun_family;               /* AF_UNIX */
    char        sun_path[108];            /* pathname */
};

所以我猜我们可以简单地执行 strlen(sun_path) + sizeof(sun_family) 我不明白他们添加的 +1。你能解释一下吗?我理解 offsetof 用于描述的可移植性

On Linux, the above offsetof() expression equates to the same value as sizeof(sa_family_t), but some other implementations include other fields before sun_path, so the offsetof() expression more portably describes the size of the address structure.

但是这个+1我不清楚。

最佳答案

How to count the size of the structure?

结构的大小是sizeof(struct sockaddr_un)


I don't understand the +1 they added. Can you please give an explanation?

这里的代码试图确定结构中使用(或将要使用)的数据的长度。

offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1
  1. offsetof(struct sockaddr_un, sun_path) 这是直到但不包括 .sun_path 成员的偏移量。这是对先前成员和先前填充的数据需求的更糟糕的计算。

  2. strlen(sun_path)string 的长度.sun_path[] 中没有空字符。如果 sun_path 不包含空字符,结果是未定义的行为 (UB)。

  3. +1 用于 sun_path 中假定的空字符

这样的计算对于将struct sockaddr_un 中的数据 发送到某个地方很有用,因为数据 需求可能比 少得多结构需要。


I would guess that we can simply do strlen(sun_path) + sizeof(sun_family)

这是一个问题(取决于使用情况)因为

1) 不包含空字符

2) 它不考虑成员 .sun_family.sun_path 之间的潜在填充。尽管在这种情况下我会很惊讶地看到任何东西。

关于c - 如何计算结构的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53664244/

相关文章:

c++ - USB2Serial 的 Linux IOCTL

c - 动态结构数组

c - 如何打印结构的各个成员

go - 如何获取结构中嵌入 slice 的内存地址?

c - 如何在二进制搜索算法中找到倍数

linux - Linux下如何识别USB Storage "volume name"?

c - Variadic 函数在 Win32 中有效,但在 Win64 中无效

java - Linux 中的运行时执行问题

c - 在 Linux C 中检索 DHCP 分配的域后缀

c - C 中的矩阵乘法无法正常工作