【发布时间】:2015-02-13 03:30:30
【问题描述】:
我知道关于这个话题有很多问题,但我仍然感到困惑。
我编写了这个简单的程序来帮助我在 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;
}
这很好用,但我对对齐感到困惑。
使用这些参数(对齐=8 字节,大小=12):
allocation successful
location of struct: 0x205e010
location of int: 0x205e010
location of short: 0x205e014
location of char: 0x205e016
sizeof struct: 8
int 是结构的最大元素,占 4 个字节。我可以在这里看到short 开始于 4 个字节之后,char 开始于 2 个字节之后。为什么short 和char 之间没有另外 2 个字节的填充?
另外,如果我使用 4 字节对齐,为什么分配会失败?既然这是struct 中最大元素的大小,难道不应该工作吗?
allocation failed
location of struct: (nil)
location of int: (nil)
location of short: 0x4
location of char: 0x6
sizeof struct: 8
【问题讨论】:
-
我很好奇:你为什么要分配一个硬编码的
12字节而不是sizeof(struct S)字节?
标签: c memory-management struct alignment posix