c语言中struct的结构体的内存分配解析 测试环境:4.10.0-38-generic #42~16.04.1-Ubuntu SMP Tue Oct 10 16:32:20 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.11)
代码如下
#include<stdio.h>
#include<string.h>
struct example1
{
int a;
int b;
char c;
char d;
double e;
};
struct example2
{
int a;
char c;
int b;
double e;
char d;
};
int main()
{
int i;
struct example1 ex1 = {1, 2, 'a', 'b', 99.9};
struct example2 ex2 = {1, 'a', 2, 'b', 99.9};
printf("size of structure ex1 in bytes %d\n", sizeof(ex1));
printf("size of structure ex2 in bytes %d\n", sizeof(ex2));
printf("Address of ex1.a = %u\n", &ex1.a);
printf("Address of ex1.b = %u\n", &ex1.b);
printf("Address of ex1.c= %u\n", &ex1.c);
printf("Address of ex1.d = %u\n", &ex1.d);
printf("Address of ex1.e = %u\n",&ex1.e);
printf("Address of ex2.a = %u\n", &ex2.a);
printf("Address of ex2.c = %u\n", &ex2.c);
printf("Address of ex2.b= %u\n", &ex2.b);
printf("Address of ex2.e = %u\n", &ex2.e);
printf("Address of ex2.d = %u\n",&ex2.d);
return 0;
}
output:
size of structure ex1 in bytes 24
size of structure ex2 in bytes 32
Address of ex1.a = 1108104576
Address of ex1.b = 1108104580
Address of ex1.c= 1108104584
Address of ex1.d = 1108104585
Address of ex1.e = 1108104592
Address of ex2.a = 1108104608
Address of ex2.c = 1108104612
Address of ex2.b= 1108104616
Address of ex2.e = 1108104624
Address of ex2.d = 1108104632
struct example1 { int a; int b; char c; char d; double e; };
int a; 4字节 1108104576
int b: 4字节 1108104580
char c:1字节 1108104584
char d:1字节 1108104585
double e:8字节 1108104592 这里double类型是8字节类型,如果e直接放入到d后面保存,那么地址e必定不能以8字节对齐,所以char d后面将会填充6个
数据 byte达到8字节对齐的目的。
编译器按照成员列表的顺序一个接一个的地给每个成员分配内存。只有当存储成员需要满足正确的边界对齐要求时,成员间才需要填充内存空间。
分析结构体example2
int a; 4个字节
char c 1个字节,因为下个元素是int型,要季节对齐,所以填充3个byte空数据。
int b 4个字节,下个元素double类型,8字节对齐,这里填充4个byte空数据。
double e 8个字节
char d 1个字节, 以结构体中最大类型字节对齐,这里结构体是最大字节类型double类型,所以需要8字节对齐。所以这里要填充7个byte空数据。
所以 结构体example2占用内存为 4+4+8+8+8 = 32 byte。
来源:oschina
链接:https://my.oschina.net/u/2614497/blog/3161685