GCC下结构体内存对齐问题

  • 格式:docx
  • 大小:14.13 KB
  • 文档页数:6

引言:结构对齐的目的是为了加快CPU取数据时的速度,不同的编译器有不同的标准,有关于4字节对齐的,也有关于8字节对齐的,解题时需跟据环境具体分析。

环境:ubuntu10.10 gcc
判断结构大小,只需要注意两点即可:
1.分析结构成员:
小于4字节的结构成员,相对起始地址要在成员大小的倍数上
Char 1 char 类型可以从任何地址开始
Short 2 short 类型需要相对结构起始地址以2 的倍数处开始
Int 4
大于4 4 对齐如double 大小为8字节,只需按4字节对齐即可
2.整个结构要关于最大的成员大小对齐(不大于4)
如果结构最大的成员是short 那么结构的大小应是2 的倍数,(不足时在结构末尾补足)如果最大成员是int ,则应是4 的倍数。

如果是double ,则是4 的倍数。

为什么是4 的倍数?
这是GCC默认的对齐大小,可以修改。

VC下应该默认是8。

测试,以下结构的大小是?
struct com
{
char c1; 1字节由下面的对齐知道占用了4 字节
long tt; 关于4 字节对齐占用了4 字节
int c9; 关于4 字节对齐占用了4 字节
short c3; 关于2 字节对齐占用了4 字节
double c4; 关于4字节对齐占用了8 字节
}; 4 的倍数,所以大小共24 字节。

struct T
{
char a;
double b;
};
struct TT
{
short a;
char b;
short aa;
};
struct A
char c;
double d;
short s;
char sf[5]; };
struct B
{
short s;
char sf[5];
char c;
double d; };
struct C
{
char c;
short s;
char sf[5];
double d; };
struct D
{
double d;
char sf[5];
short s;
char c; };
struct E
{
char c;
char sf[5];
double d;
short s; };
#include <stdio.h>
struct A
{ //QT/Cfree下GCC下char c; //8byte 4
double d; //8byte 8
short s; //7byte 4
char sf[5];//2 4
}a1;
//24
struct B
{
short s; //7byte 2
char sf[5];//0 5
char c; //1byte 1
double d; //8byte 8
}a2;
//16
struct C
{
char c; //2byte 1
short s; //7byte
char sf[5];//7
double d; //8byte
}a3;
//24
struct D
{
double d; //13byte
char sf[5];//1
short s; //2byte
char c; //8byte
}a4;
int main()
{
/* a.c='a';
a.d=5.2356;
a.s=3;
// a.sf[5]="xuwe";不能这样赋值*/
printf("%d\n",sizeof(a1));
printf("%d\n",sizeof(a2));
printf("%d\n",sizeof(a3));
printf("%d\n",sizeof(a4));
//struct A a1={'a',5.2356,3,"xuwe"};
printf("%d\n",&a1.c);
printf("%d\n",&a1.d);
printf("%d\n",&a1.s);
printf("%d\n",&a1.sf[5]);
printf("\n");
printf("%d\n",&a2.s);
printf("%d\n",&a2.sf[5]);
printf("%d\n",&a2.c);
printf("%d\n",&a2.d);
printf("\n");
printf("%d\n",&a3.c);
printf("%d\n",&a3.s);
printf("%d\n",&a3.sf[5]);
printf("%d\n",&a3.d);
printf("\n");
printf("%d\n",&a4.d);
printf("%d\n",&a4.sf[5]);
printf("%d\n",&a4.s);
printf("%d\n",&a4.c);
printf("\n");
return 0;
}。