关于字节对齐的sizeof的讨论
- 格式:doc
- 大小:24.00 KB
- 文档页数:2
对C语言中的sizeof的介绍分析对C语言中的sizeof的介绍分析引导语::sizeof是C语言中判断数据类型或者表达式长度符,以下是店铺分享给大家的对C语言中的sizeof的介绍分析,欢迎阅读!1.定义sizeof是C/C++中的一个操作符(operator),作用就是返回一个对象或者类型所占的内存字节数。
返回值类型为size_t,在头文件stddef.h中定义。
这是一个依赖于编译系统的值,一般定义为typedef unsigned int size_t;编译器林林总总,但作为一个规范,都会保证char、signed char和unsigned char的sizeof值为1,毕竟char是编程能用的最小数据类型。
MSDN上的解释为:The sizeof keyword gives the amount of storage, in bytes, associated with avariable or atype (including aggregate types). This keyword returns a value of typesize_t.2. 语法:sizeof有三种语法形式,如下:1) sizeof( object ); // sizeof( 对象 );2) sizeof( type_name ); // sizeof( 类型 );3) sizeof object; // sizeof 对象;所以一下三种sizeof的使用都是对的复制代码代码如下:#includemain(){int b;printf("%dn",sizeof b);printf("%dn",sizeof(b));printf("%dn",sizeof(int));}3. 基本数据类型的sizeof这里的基本数据类型指short、int、long、float、double这样的简单内置数据类型,由于它们都是和系统相关的,所以在不同的系统下取值可能不同,这务必引起我们的注意,尽量不要在这方面给自己程序的移植造成麻烦。
字节对齐原则这个问题也是困扰了我很久的⼀个问题:为了加快数据存取的速度,编译器默认情况下会对结构体成员和结构体本⾝存储位置进⾏处理,使其存放的起始地址是⼀定字节数的倍数,⽽不是顺序存放,称为字节对齐.设对齐字节数为n(n = 1,2,4,8,16),每个成员内存长度为Li,Max(Li)为最⼤的成员内存长度,字节对齐规则是:1. 结构体对象的起始地址能够被Max(Li)所整除;2. 结构体中每个成员相对于起始地址的偏移量,即对齐值应是min(n,Li)的倍数.若不满⾜对齐值的要求,编译器会在成员之间填充若⼲个字节;3. 结构体的总长度值应是min(n,Max)(Li)的倍数,若不满⾜总长度值的要求,编译器在为最后⼀个成员分配空间后,会在其后填充若⼲个字节. (VC默认的对齐字节数n=8)开不懂,请看下⾯例⼦:#include <iostream>using namespace std;// 1加1+编译器补充的2个再加上int 的4个(编译器⾃动加的)typedef struct node1 // 1+1+(2)+4 = 8{char c1;char c2;int a;}str1 ;typedef struct str2 // 1+(3)+4+1+(3) = 12{char c1;int a;char c2;}str2 ;typedef struct str3 // 5+(3)+4+2+(2) = 16{char c1[5];int b;short c;}str3 ;typedef struct str4 // 5+(1)+(2)+4 = 12{char c1[5];short c;int b;}str4 ;typedef struct str5 // 1+1+(6)+8 = 16{char c1;char c2;double a;}str5 ;typedef struct str6 // 1+(7)+8+1+(7) = 24{char c1;double a;char c2;}str6 ;typedef struct str7{char c1;str1 s; // 相当于吧str1的结构放在这 char,char,intdouble b;}str7 ; // 1+1+1+(1)+4+4 = 12int main(){str1 s1;str2 s2;str3 s3;str4 s4;str5 s5;str5 s6;str7 s7;str8 s8;cout << "s1 = " << sizeof(s1)<<endl;cout << "s2 = " << sizeof(s2)<<endl; cout << "s3 = " << sizeof(s3)<<endl; cout << "s4 = " << sizeof(s4)<<endl; cout << "s5 = " << sizeof(s5)<<endl; cout << "s6 = " << sizeof(s6)<<endl; cout << "s7 = " << sizeof(s7)<<endl; cout << "s8 = " << sizeof(s8)<<endl; return0;}图解:str1str2:str3:str4:str5:str6:。
C语言结构体中的数组字节对齐在C语言中,结构体是一种用户自定义的数据类型,用于将不同类型的数据组合在一起。
结构体中常常包含多个成员变量,其中可能有数组类型的成员变量。
在结构体中使用数组时,需要了解数组字节对齐的概念和规则,以确保内存的最佳利用和访问的效率。
什么是字节对齐字节对齐是指在将数据存储在计算机内存中时,按照特定规则进行调整,以确保数据的存储和访问的效率。
字节对齐的规则可以对齐数据的起始地址或者数据的长度。
计算机中的数据存储是按照字节(Byte)来划分的,一个字节通常由8个二进制位组成。
字节对齐的主要目的是为了节省内存和提高访问效率。
在C语言中,结构体中的成员变量通常按照字节对齐的规则来排列。
C语言结构体中的数组字节对齐规则在C语言中,结构体中的数组字节对齐规则通常遵循以下原则:1.结构体的起始地址必须是所有成员变量所要求对齐方式的最小公倍数。
2.结构体中的每个成员变量的地址必须是它本身的大小的整数倍。
3.结构体的总大小必须是其最大成员变量大小的整数倍。
根据字节对齐规则,如果结构体中的成员变量的累计大小不是字节对齐的倍数,编译器会在成员变量之间添加填充字节,以满足对齐要求。
这些填充字节在结构体的占用空间中不可访问。
填充字节的目的是将后续成员变量的地址对齐,以提高内存访问效率。
数组字节对齐的示例为了更好地理解数组字节对齐的规则,我们来看一个示例。
#include <stdio.h>struct MyStruct {char c;int i;char arr[3];};int main() {struct MyStruct s;printf("sizeof(MyStruct) = %lu\n", sizeof(struct MyStruct));printf("sizeof(s.c) = %lu\n", sizeof(s.c));printf("sizeof(s.i) = %lu\n", sizeof(s.i));printf("sizeof(s.arr) = %lu\n", sizeof(s.arr));return 0;}输出结果:sizeof(MyStruct) = 12sizeof(s.c) = 1sizeof(s.i) = 4sizeof(s.arr) = 3在这个示例中,我们定义了一个包含一个字符类型变量、一个整型变量和一个长度为3的字符数组的结构体MyStruct。
C语言字节对齐字节对齐的由来程序在运行时会将数据临时存放在内存中,芯片内核需要对这些数据进行计算,不断的读取内存以获得数据,并将计算结果写入内存。
计算机体系经过若干年的发展,最终确定了以8bits作为其基本的存储单元——byte(字节),这是每个地址所对应的最小访问单元,在C语言中对应一个char型的变量。
下图为芯片内核访问内存的示意图。
芯片内核通过控制总线控制内存的动作,通过地址总线告知内存地址,数据总线上出现交互的数据。
图1访问内存示意图假设上图是8位机的示意图,那么数据总线的宽度是8bits,由8根数据线组成,这样芯片内核与内存之间一次就可以同时交换8个bits的数据,正好是一个字节。
图中右侧的每个小格子代表一个存储地址,对应一个字节。
下面通过一段C语言代码来具体看看芯片内核与内存之间的数据交互过程。
char data[2];data[0]=2;data[1]=data[0]+1;第一行代码定义了2个字节的数组data。
假设data数组被编译到地址0x100,那么data[0]这个字节就被存储在地址为0x100的内存空间,data[1]这个字节就被存储在地址为0x101的内存空间。
第二行对应的硬件动作是将数据2存入到data[0]中,也就是将数据2存入到内存中的0x100地址,执行这条语句时,芯片内核对控制总线、地址总线和数据总线进行操作,控制总线上出现写信号,地址总线上出现数据0x100,数据总线上出现数据0x02。
此时内存就知道需要将数据2写入到地址0x100中,完成一次写操作。
第三行先读出data[0]中的数据,芯片内核将控制总线置为读信号,将地址总线置为0x100,此时,内存就会从其内部取出0x100地址中的数据,也就是数据2,2将出现在数据总线上,此时芯片内核就会通过数据总线读取到data[0]中的数据了。
接下来芯片内核计算2+1=3,需要将数字3写入到data[1]中,芯片内核将控制总线置为写信号,将地址总线置为0x101,将数据总线置为3,内存接收到这些信号后,就会将数据3存入到其内部0x101地址中,完成本次操作。
C语言结构体对齐问题1。
几个结构体例子:struct{short a1;short a2;short a3;}A;struct{long a1;short a2;}B;sizeof( A)=6, sizeof( B)=8,为什么?注:sizeof(short)=2,sizeof(long)=4因为:“成员对齐有一个重要的条件,即每个成员按自己的方式对齐。
其对齐的规则是,每个成员按其类型的对齐参数(通常是这个类型的大小)和指定对齐参数(这里默认是8字节)中较小的一个对齐。
并且结构的长度必须为所用过的所有对齐参数的整数倍,不够就补空字节。
”(引用)结构体A中有3个short类型变量,各自以2字节对齐,结构体对齐参数按默认的8字节对齐,则a1,a2,a3都取2字节对齐,则sizeof(A)为6,其也是2的整数倍;B中a1为4字节对齐,a2为2字节对齐,结构体默认对齐参数为8,则a1取4字节对齐,a2取2字节对齐,结构体大小6字节,6不为4的整数倍,补空字节,增到8时,符合所有条件,则sizeof(B)为8;可以设置成对齐的#pragma pack(1)#pragma pack(push)#pragma pack(1)struct{short a1;short a2;short a3;}A;struct{long a1;short a2;}B;#pragma pack(pop)结果为sizeof( A)=6,sizeof( B)=6 ************************#pragma pack(8)struct S1{char a;long b;};struct S2 {char c;struct S1 d;long long e;};#pragma pack()sizeof(S2)结果为24.成员对齐有一个重要的条件,即每个成员分别对齐,即每个成员按自己的方式对齐。
也就是说上面虽然指定了按8字节对齐,但并不是所有的成员都是以8字节对齐。
结构体字节对齐的方法全文共四篇示例,供读者参考第一篇示例:结构体字节对齐是编程中一个非常重要的概念,尤其在涉及到内存对齐的底层编程中更是不可或缺。
在结构体的定义中,每个元素都需要在内存中占用一定的空间,而结构体整体的大小受到字节对齐规则的限制。
本文将介绍结构体字节对齐的方法及其原理,希望能帮助读者更好地理解和掌握这一概念。
一、什么是字节对齐字节对齐是指在结构体中每个元素按照特定的规则分配内存空间,以便提高内存读取的效率。
在计算机系统中,一般要求数据在内存中的存储地址是某个特定值的倍数,这个特定值就是对齐系数。
常用的对齐系数有1、2、4、8等,根据不同的系统和编译器,对齐系数可能会有所不同。
二、结构体字节对齐的原理在C语言中,结构体的内存对齐是通过编译器来进行处理的。
当定义一个结构体时,编译器会按照一定的规则对结构体中的元素进行字节对齐,以便提高读取效率。
具体的对齐规则如下:1. 结构体中每个元素的偏移量必须是它自身类型大小的整数倍。
2. 结构体的大小必须是最大元素类型大小的整数倍。
3. 结构体的对齐系数为结构体中所有元素类型大小的最大值。
通过这些规则,编译器可以在编译时确定结构体的大小,并根据对齐系数进行内存对齐,从而提高内存访问的效率。
1. 使用#pragma pack指令在C语言中,可以使用#pragma pack指令来改变编译器默认的对齐系数。
通过指定pack(n)来设置n值,表示结构体的对齐系数为n。
这样可以在需要的时候自定义结构体的对齐系数,提高程序的效率。
```c#pragma pack(1)struct Student {char name[10];int age;float score;};```上面的代码中,通过#pragma pack(1)改变了结构体的对齐系数为1,从而可以确保结构体中的每个元素都按照一个字节进行对齐。
2. 使用__attribute__((packed))关键字在GCC编译器中,可以使用__attribute__((packed))关键字来实现对齐系数的设置。
对对齐(alignment)的一些认识关于内存地址对齐,尤其是struct中成员的对齐导致的struct的size问题很多人(包括我:()似乎都没有一个比较清晰的认识,所以产生了整理这方面思路和帖子的想法,下面的文字是资料、文档、实验和推测的混合体,有错误是肯定的:)。
能给您提供一点帮助,是我最大的愿望。
(有点麻了)引:struct s {char c;int i;}; 在sizeof(char)=1 sizeof(int)=4的情况下sizeof(struct s)为什么经常是8不是5?这个就是对齐(alignment)的缘故。
那么什么是对齐?现代计算机中内存空间都是按照byte划分的,从理论上讲似乎对任何类型的变量的访问可以从任何地址开始,但实际情况是在访问特定变量的时候经常在特定的内存地址访问,这就是对齐。
为什么呢?msdn for vc6中有这么一段:This principle is especially important when you write code for porting to multiple processors. A misaligned 4-byte data member, which is on an address that is not a multiple of four, causes a performance penalty with an 80386 processor and a hardware exception with a MIPS® RISC processor. In the latter case, although the system handles the exception, the performance penalty is significantly greater.大意是:1.某些硬件平台只能在某些地址处取某些特定类型的数据,否则抛出硬件异常。
一、sizeof的概念sizeof是C语言的一种单目操作符,如C语言的其他操作符++、--等。
它并不是函数。
sizeof操作符以字节形式给出了其操作数的存储大小。
操作数可以是一个表达式或括在括号内的类型名。
操作数的存储大小由操作数的类型决定。
二、sizeof的使用方法1、用于数据类型sizeof使用形式:sizeof(type)数据类型必须用括号括住。
如sizeof(int)。
2、用于变量sizeof使用形式:sizeof(var_name)或sizeof var_name变量名可以不用括号括住。
如sizeof (var_name),sizeof var_name等都是正确形式。
带括号的用法更普遍,大多数程序员采用这种形式。
注意:sizeof操作符不能用于函数类型,不完全类型或位字段。
不完全类型指具有未知存储大小的数据类型,如未知存储大小的数组类型、未知内容的结构或联合类型、void类型等。
如sizeof(max)若此时变量max定义为int max(),sizeof(char_v) 若此时char_v定义为char char_v [MAX]且MAX未知,sizeof(void)都不是正确形式。
三、sizeof的结果sizeof操作符的结果类型是size_t,它在头文件中typedef为unsignedint类型。
该类型保证能容纳实现所建立的最大对象的字节大小。
1、若操作数具有类型char、unsigned char或signed char,其结果等于1。
ANSI C正式规定字符类型为1字节。
2、int、unsigned int 、short int、unsigned short 、long int 、unsigned long 、float、double、long double类型的sizeof 在ANSI C中没有具体规定,大小依赖于实现,一般可能分别为2、2、2、2、4、4、4、8、10。
字节对齐详解(Byte alignment)字节对齐详解(Byte alignment)Byte alignment detail - jack-wang - C++ blogJack-wangC++ blog home new essays contact polymerization managementEssays, -107 reviews, -17 articles, -0, trackbacks-0Byte alignmentI. what is byte alignment and why should it be aligned?The memory space of modern computer are in accordance with the byte classification, in theory seems to be of any type of variable access can start from any address, but the actual situation is when accessing a specific type variables often inFixed memory address access, which requires various types of data to be arranged in space in accordance with certain rules, rather than sequential emissions one after another, which is alignment.The role and reason of alignment: each hardware platform is very different from the processing of storage space. Some platforms can access certain types of data only from certain addresses. For example, some of the schema's CPU is in accessWhen a variable is not aligned after an error, so in thisframework must be byte aligned. Other programming platform is likely not the case, but the most common is the platform for if not in accordance with the requirements ofData storage alignment results in loss of access efficiency. Some platforms, for example, start reading from my address at any time, if a int (assuming 32 bit system) is stored at the beginning of my addressA read cycle can read the 32bit, and if stored at the start of the odd address, 2 read cycles are needed, and the number of bits and bytes of the two read results are pieced together to obtain the 32bit number According to the. Obviously, the reading efficiency has dropped a lot.Two. Byte alignment affects the program:Let's look at some examples first (32bit, x86 environment, gcc compiler):Set the structure as follows:Struct A{Int a;Char b;Short c;};Struct B{Char b;Int a;Short c;};It is now known that the length of various data types on 32machines is as follows:Char:1 (signed, unsigned, identical)Short:2 (signed, unsigned, identical)Int:4 (signed, unsigned, identical)Long:4 (signed, unsigned, identical)Float:4 double:8So, what's the size of the two structures above?As a result:The value of sizeof (strcut, A) is 8The value of sizeof (struct, B) is 12The structure A contains 4 bytes of length int, one char with 1 byte length, one short type data with 2 byte length, and the same for B, and the size of A and B should be 7 bytes, as a rule.The result is that the compiler aligns the data members in space. This is the result of the alignment of the compiler's default settings, so can we change the default alignment settings for the compiler, of course, for example:#pragma pack (2) / * specified by 2 byte aligned.Struct C{Char b;Int a;Short c;};#pragma (pack) / * to cancel the specified alignment, restoredefault alignment.The sizeof (struct, C) value is 8.Change the alignment value to 1:#pragma pack (1) / * specified by 1 byte aligned.Struct D{Char b;Int a;Short c;};#pragma (pack) / * to cancel the specified alignment, restoredefault alignment.The value of sizeof (struct, D) is 7.Later we will explain the role of #pragma pack ()Three. What sort of principles does the compiler align?First, let's look at four important basic concepts:1. the alignment value of the data type itself:For type char data, its own alignment value is 1, for short type 2, and for int, float, and double types, its alignment value is 4, in bytes.TwoThe self aligned value of a structure or class: the value of the maximum value of its own alignment in its members.3. specifies the alignment value: #pragma pack (value) when the specified alignment value is value.4. valid alignment values for data members, structures, and classes: the value of the self aligned value and the specified alignment value.With these values, we can easily discuss the members of specificdata structures and how they align themselves. The valid alignment value, N, is the most important value that ultimately determines the way the data is stored. Valid alignment N, that isIndicates alignment on N, that is to say, the data storage start address%N=0, and the data variables in the data structure are emitted in defined order. The starting address of the first data variable is the numberAccording to the starting address of the structure. The member variables of the structure are aligned to be emitted, and the structure itself is rounded according to its own valid alignmentvalue (i.e., the total length of the member variable of the structure is required to be an integer to the effective alignment of the structure Times, combined with the following examples to understand. Then you can't understand the value of several examples above.Example analysis:Analysis example B;Struct B{Char b;Int a;Short c;};Assume that B starts emission from address space 0x0000. The specified alignment value is not defined in this example. In theauthor's environment, the value is default to 4. The first member variable, B, has its own alignment value of 1, specified or specified by defaultThe alignment value is 4 small, so the valid alignment valueis 1, so the storage address 0x0000 conforms to the 0x0000%1=0. second member variable a, with its own alignment value of 4, so thevalid alignment value is also 4,So you can only check the 0x0004%4=0 in the four contiguous bytes space of the start address 0x0004 to 0x0007, and close to the first variable. The third variable, C, has its own alignment value 2, so the valid alignment value is also 2, and can be stored in the two byte spaces of 0x0008 to 0x0009, which conforms to 0x0008%2=0. Soit's stored from 0x0000 to 0x0009It's all B content. Looking at the data structure, the B's own alignment value is the maximum alignment value in its variables (here is b), so it's 4, so the valid alignment value of the structure is 4. According to the requirement of structure rounding,0x0009 to 0x0000=10 bytes (%4 = 0, 102). Therefore, 0x0000A to0x000B is also occupied by the structure B. Therefore, B from 0x0000 to 0x000BThere are 12 bytes, sizeof (struct, B) =12; in fact, if this is the case, it will be byte aligned,Because its starting address is 0, so it must be aligned to 2 bytes, is added in the back, in order to realize the efficiency of access is because the compiler structure array, if we define an array ofstructures of the B, theWhat is the starting address of the first structure 0 no problem,but the second structure? According to the definition of arrays, all the elements in the array are close to, if we do not take the size of the structure of an integer multiple of 4, then the nextThe starting address of the structure will be 0x0000A, which obviously does not satisfy the address alignment of the structure, so we need to add the structure to an integer multiple of the valid alignment size. In fact, for example, for type char data, theThe self alignment value is 1, and for short type 2, for int, float, and double types, the self alignment value is 4. These existing types of self alignment values are also considered on an array basis Because these types of length are known, their own alignment values are knownSimilarly, analyze the example above, C:#pragma pack (2) / * specified by 2 byte aligned.Struct C{Char b;Int a;Short c;};#pragma (pack) / * to cancel the specified alignment, restoredefault alignment.The first variable B has its own alignment value of 1 and specifies the alignment value of 2, so its valid alignment value is 1. Assuming that C starts from 0x0000, then B is stored in 0x0000 and conforms to0x0000%1=0. Second variables, the self aligned value of 4, and the specified alignment value of 2,So the valid alignment value is 2, so the order is stored in four successive 0x0002, 0x0003, 0x0004, and 0x0005Byte, in line with 0x0002%2=0. The third variable C has its own alignment value of 2, so the valid alignment value is 2, sequentially storedIn 0x0006, 0x0007, in line with0x0006%2=0. So, from 0x0000 to 0x00007, the C variables are storedin the eight character section. Again, the C's own alignment value is 4, so the valid alignment value of C is 2. And 8%2=0, COnly takes eight bytes from 0x0000 to 0x0007. So sizeof (struct,C) =8.Four. How do you modify the default alignment value of the compiler?1. in VC IDE, you can modify this: [Project]|[Settings], the c/c++ tab, the Code Generation option of Category, and the Struct In Member Alignment, the default is 8 bytes.2., when encoding, you can do this dynamically: #pragma pack. Note: pragma, not progma.Five. For byte alignment, how do we consider it in programming?If the time in the program to consider saving space, so we only need to assume that the structure of the first address is 0, then all the variables are arranged in accordance with the above principles, the basic principle is to structure the variables according to the From small to large size type declaration, to minimize the intermediate fill space. There is a space for time for efficiency, we show to fill the space of alignment, for example: there is a use of space for time to doThe method is explicitly inserted into the reserved member:Struct A{Char a;Char reserved[3]; / / use space for timeInt b;}Reserved members do not have what meaning to our program, it is only to fill the space in order to achieve the purpose of byte alignment, ofcourse, if not with the compiler will automatically fill the members usually aligned to us, our own plus it is up to the explicit reminder.Six. The potential danger of byte alignment:Many of the hidden problems in the code about alignment are implicit. For example, when forced type conversions are used. Such as: Unsigned, int, I = 0x12345678;Unsigned char *p=NULL;Unsigned short *p1=NULL;P=&i;*p=0x00;P1= (unsigned, short *) (p+1);*p1=0x0000;The last two codes, which access the unsignedshort - type variables from the odd bounds, clearly do not conform to the rules of alignment.On X86, similar operations only affect efficiency, but on MIPS or SPARC, it might be a error because they require byte alignment Seven. How to find problems with byte alignment:If alignment or assignment occurs, check first1. compiler big little side settings2. see if the system itself supports non aligned access3. if the support view is set justified or not, then if you look at the visit, you need to add some special modifiers to mark its special access operation.Eight. Related articles: transferred fromAlignment processing under ARMFrom DUI0067D_ADS1_2_CompLib3.13 type qulifiersSome are extracted from the ARM compiler document alignment section Align use:1.__align (Num)This is used to modify the byte boundary of the highest level object. When using LDRD or STRD in assemblyYou'll need to use this command __align (8) to modify restrictions.To ensure that the data objects are aligned accordingly.The modifier object's command is 8 bytes maximum, allowing 2 bytesof objects to be 4 bytesAlign, but cannot align 4 bytes of object with 2 bytes.__align is a storage class modification that only modifies the superlative type objects and cannot be used for structure or function objects.2.__packed__packed is performing a byte alignment1. cannot align packed objectsTwoRead and write access to all objects is non aligned3.float and float containing structures, together and unused__packed objects, cannot be byte aligned4.__packed has no influence on the local shaping variables5., the transformation from unpacked object to packed object is undefined, and the plastic pointer can be legalMeaning "packed".__packed int* p; //__packed int does not make sense6. aligned or non aligned read and write access poses problems__packed struct STRUCT_TEST{Char a;Int b;Char c;This structure is defined as follows}; / / b starting address is not alignedVisit B / / may have problems in the stack, the stack must be aligned because data access [from CL]The following variables are defined as global / static on the stack Static char* p;Static struct STRUCT_TEST a;Void, Main (){__packed int* Q; / / this is defined as __packed to modify the current Q to the non aligned data can address accessP = (char*) &a;Q = (int*) (p+1);*q = 0x87654321;*The assembly instructions that receive the assignments are clear LDR r5,0x20001590 = = #0x12345678[0xe1a00005], MOV, R0, R5[0xeb0000b0] BL __rt_uwrite4 / / here to call a write operation of4byte function[0xe5c10000] STRB R0, [r1, #0] / / function for 4 STRB operation and then return to ensure the data correct access[0xe1a02420], MOV, R2, R0, LSR, #8[0xe5c12001], STRB, R2, [r1, #1][0xe1a02820], MOV, R2, R0, LSR, #16[0xe5c12002], STRB, R2, [r1, #2][0xe1a02c20], MOV, R2, R0, LSR, #24[0xe5c12003], STRB, R2, [r1, #3][0xe1a0f00e], MOV, PC, R14* /*If Q does not add a __packed modifier, the assembly instruction is such that it leads to an incorrect access to the odd address [0xe59f2018] LDR r2,0x20001594 = = #0x87654321[0xe5812000], STR, R2, [r1, #0]* // / this can clearly see how non aligned access error/ / and how to eliminate the non aligned access problemsCan also see the difference of instruction / / non aligned access and access to the efficiency problem of alignment}This article from CSDN blog, reprinted please indicate the source: Posted, on, 2010-03-17, 15:55 Wang read (107) review (0) edit, collection, reference, classification: c++ programming foundation Grand Bambook program up to the competitionIT news:Microsoft and Google clash over the release of zero day vulnerabilities? 2011 CES Preview: Microsoft will push Windows TVSources said Qualcomm will acquire Atheros communications for $3 billion 500 million? motorcycle solutions division CEO: this year will be distributed to shareholders? China Unicom opened 5 national roaming packages: unlimited daily limit of 150 yuanRecommended position:Beijing Internet era looking for C++ Development EngineerBlogger Park asks IT journalism English C++ programmer for recruitmentTitle, please enter a titleName, please enter your namehomepagePlease enter a verification codeVerification code *After the submission fails, you can enter the comment content by restoring the last commit to restoring the newly submitted content Remember Me?The new user registration login using advanced comment. Restorethe last commit[use the Ctrl+Enter key to submit directly]10 minutes a day, easy to learn EnglishRecommended position:.NET Development Engineer (Beijing century InBev).NET Senior Software Engineer (Suzhou purchase information)- site operators (Suzhou purchase information).NET Development Engineer (Beijing Internet Era)(].NET/Web Development Engineer (Wuhan information technology)?.NET Development Engineer (Shanghai, unrivaled network)Windows C++ (Beijing Internet Era)- senior (Shanghai network)Blog home essay:? cloud computing - from infrastructure to application architecture - the concept of cloud computing? setting up the Android situational model? Delphi XE RTTI enhancements, dynamic Hook, certain internal eventsSimilarly, programmers are careless about their strengths, and are motivated to stay positive for the next 10 yearsMonthly information two-dimensional coordinate drawing - (draw arrows perfect algorithm) continued IIKnowledge base:Coordinate high speed insertion, movement, and query algorithms In MVC2.0, using Lodop for WEB printing presents the perfect solutionPHP best practices? discussion of procedural costsC#'s secret secret - buffer overflowRelated articles:Several basic library functions, memosThe automatic generation of the macro - diabolic tricks and wicked craft codeVS2005/2008, warning, C4251, needs, to, have, dll-interfaceByte alignmentFour major features of Visual C++2010's c++ languageToday, I suddenly mentioned stdcall in my work. I forgot something about it. I was almost asked by the supervisor and reviewed it again Fastest speed to find memory leaksSite navigation:Blog, IT news blog, personal homepage, BlogJava blog, life blog, IT blog, PHP blog, blog, community managementThe most concise reading format:Byte alignmentMarch, <2010 >Day 123456Twenty-eight million one hundred and twenty-three thousand four hundred and fifty-sixSeventy-eight billion nine hundred and ten million one hundred and eleven thousand two hundred and thirteenFourteen trillion and one hundred and fifty-one billion six hundred and seventeen million one hundred and eighty-one thousand nine hundred and twentyTwenty-one trillion and two hundred and twenty-two billion three hundred and twenty-four million two hundred and fifty-two thousand six hundred and twenty-sevenTwenty-eight billion two hundred and ninety-three million thirty-one thousand one hundred and twenty-threeForty-five million six hundred and seventy-eight thousand nine hundred and tenLinks to my essayMy commentEssays I participate inMessage book (1) leave a message for meView public messagesView private messagesEssay classification (103) C# column Fundamentals of c++ programming (7) DB (3)Java column (2)Linux column (9)STL, Boost (6)VC column (7)Web development (1)Operating system (1)Multicore programming (3)Distributed system (4)Compilation (1)Open source project (2)Other (9)Software Engineering (1)Design patterns (5)Algorithms and data structures (1) Network communication (15)Game server development (15)Game engine (11)Essay archives (107) December 2010 (1) November 2010 (7)October 2010 (7)September 2010 (2)August 2010 (2)July 2010 (3)June 2010 (3)May 2010 (1)April 2010 (4)March 2010 (6)February 2010 (12)January 2010 (22)December 2009 (1)November 2009 (7)August 2009 (5)June 2009 (4)February 2009 (4)January 2009 (15)October 2008 (1)LinuxchinaunixGame development gold celebrationCloud windSynthetic IntelLambda -calculusChau wai MingThe latest essay 1. what you need to know as a good programmer2. error LNK2019: cannot resolve the external symbol__imp___CrtDbgReportW3., VS2005 complains about finding libc.lib problems4., there was a game called legend5. using Eclipse platform for C/C++ development6. Development Notes: install JDK 6 and Eclipse under Ubuntu7. compile openfetion28. compile Openfetion9. Ubuntu9.10 VI under the arrow keys into ABCD solution10. programmers must know the SQLSERVER database optimization techniquessearchThe latest essay 1. what you need to know as a good programmer2. error LNK2019: cannot resolve the external symbol__imp___CrtDbgReportW3., VS2005 complains about finding libc.lib problems4., there was a game called legend5. using Eclipse platform for C/C++ development6. Development Notes: install JDK 6 and Eclipse under Ubuntu7. compile openfetion28. compile Openfetion9. Ubuntu9.10 VI under the arrow keys into ABCD solution10. programmers must know the SQLSERVER database optimization techniquesThe latest review 1. re: once had a game called "legend"What a wonderful memory!--yugi2. re: company to disband. Bitter cups~ Reflect~What a cup!--2009"3. re: cannot find d3dx9_38.dll[not logged in]Can not find what to do?--ccCompile CEGUI 0.6.0 under 4. re: VS2005 environmentchaos--aaaThe automatic generation of the macro - 5. diabolic tricks andwicked craft re: code-!Pass by, you know--Kevin LynxRead list 1. VS2005 environment, compile CEGUI 0.6.0 (1202)2., known as the target software server architecture (reproduced, Ido not matter, oh, pictures are not sent, lazy) (1100)3. design of communication architecture for online games server (817)4. Google technology "Sambo" one of the Google file system and the Kosmos file system (578)5. design of server architecture for online games (562)Comment list 1. kosmix, another open source GFS like distributedfile system (3)2. company disband. Bitter cups~ Reflect~ (3)3. did not find MSVCR90.dll, so the application failed to start, and reinstalling the application might fix the problem (1)4., there was a game called legend (1)5. could not find d3dx9_38.dll (1)Powered by: blog template: Copyright 2011 Wang Hujiang blog?。
关于字节对齐的sizeof的讨论
众所周知,程序为了提高访问效率,编译器在编译的时候,进行字节对齐。
程序员也可以字节指定对齐方式。
Win32下的为progma指令,具体来说
#pragma pack(push) //保存原对齐状态
#pragma pack(4)//设定为4字节对齐
struct test
{
int a;
};
#pragma pack(pop)//恢复对齐状态
在linux下,gcc是默认的编译器。
g++ 支持progma指令,gcc也支持GNU扩展
__attribute__指令
参考《__attribute__》,对于字节对齐的举例为
struct test{
short b[3];
} __attribute__ ((aligned (8)));
__attribute__还支持aligned 和packed ,解释如下
__attribute__ ((aligned)); 选择针对目标机器最大的对齐方式,可以提高拷贝操作的效率。
aligned属性使被设置的对象占用更多的空间,相反的,使用packed可以减小对象占用的空间。
需要注意的是,attribute属性的效力与你的连接器也有关,如果你的连接器最大只支持16字节对齐,
那么你此时定义32字节对齐也是无济于事的。
__attribute__ ((packed))使用该属性可以使得变量或者结构体成员使用最小的对齐方式,即对变量是一字节对齐,
对域(field)是位对齐。
下面以pragma 来讨论指定结构体对齐方式!
总的来说规律如下
#pragma pack(n)来设定变量以n字节对齐方式。
n字节对齐就是说变量存放的起始地址的偏移量有两种情况:
第一、如果n大于等于该变量所占用的字节数,那么偏移量必须满足默认的对齐方式
第二、如果n小于该变量的类型所占用的字节数,那么偏移量为n的倍数,不用满足默认的对齐方式。
结构的总大小也有个约束条件,分下面两种情况:
如果n大于所有成员变量类型所占用的字节数,那么结构的总大小必须为占用空间最大的变量占用的空间数的倍数;
否则必须为n的倍数。
alignment (n) must be a small power of two
示例
struct test
{
char m1;
double m4;
int m3;
};
如果不指定对齐方式的话,其以double所占空间大小对齐,即
sizeof(struct test) = 24 (IA32 GCC)
此处让我想起linux中的container_of,和offset宏。