Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用posix_memalign在C中正确对齐结构?_C_Memory Management_Struct_Alignment_Posix - Fatal编程技术网

如何使用posix_memalign在C中正确对齐结构?

如何使用posix_memalign在C中正确对齐结构?,c,memory-management,struct,alignment,posix,C,Memory Management,Struct,Alignment,Posix,我知道关于这个话题有很多问题,但我仍然感到困惑 我编写了这个简单的程序来帮助我在C中可视化内存对齐: #include <stdio.h> #include <stdlib.h> struct S{ int a; short b; char c; }; int main() { struct S *s; posix_memalign((void**)&s, 8, 12) == 0 ? printf("allocation suc

我知道关于这个话题有很多问题,但我仍然感到困惑

我编写了这个简单的程序来帮助我在C中可视化内存对齐:

#include <stdio.h>
#include <stdlib.h>
struct S{
  int a;    
  short b;
  char c;
};
int main()
{
    struct S *s;
    posix_memalign((void**)&s, 8, 12) == 0 ? printf("allocation successful"):printf("allocation failed");
    printf("\nlocation of struct:\t%p\n", s);
    printf("\nlocation of int:\t%p\nlocation of short:\t%p\nlocation of char:\t%p\n", &(s->a), &(s->b), &(s->c));
    printf("\nsizeof struct: %lu\n", sizeof(s));
    free(s);
    return 0;
}
int
是结构的最大元素,有4个字节。我可以在这里看到
short
在4个字节之后开始,而
char
2个字节之后开始。为什么
short
char
之间没有另外两个字节的填充

另外,如果使用4字节的对齐方式,为什么分配会失败?因为这是
结构中最大元素的大小,所以它不应该工作吗

allocation failed
location of struct: (nil)

location of int:    (nil)
location of short:  0x4
location of char:   0x6

sizeof struct: 8

char
成员可以在任何字节边界上对齐;不需要在
char
成员之前插入填充,即使编译器可以这样做。按照布局方式,结构中只有一个填充字节。如果
short
成员后有间隙,则结构将有五个字节的填充,这是浪费

在您的机器上,
posix_memalign()
支持的最小对齐方式可能是8。POSIX说它可能会失败:

[EINVAL]
对齐参数的值不是两倍于
sizeof(void*)
的幂


话虽如此,看起来sizeof(void*)
可能是4(您打印的地址适合32位地址空间)。也许您应该打印
errno
(和/或
strerror(errno)
)以查看失败的原因。

谢谢,字符对齐很有趣。我没有读过。我不明白为什么4对齐失败,但int和short仍然由4个字节分隔。印刷史崔罗(errno)给了我:成功。也就是说,对齐设置为4,大小设置为12。另外,我得到sizeof(void*)是8个字节。@user2676680:如果
sizeof(void*)
是8个字节,那么您不能在4个字节的奇数倍的对齐上进行分配;它不符合POSIX指定的要求。我很好奇:为什么要分配硬编码的
12
字节,而不是
sizeof(struct S)
字节?
allocation failed
location of struct: (nil)

location of int:    (nil)
location of short:  0x4
location of char:   0x6

sizeof struct: 8