Last active
October 30, 2016 08:10
-
-
Save itczl22/f66cf992aa2a2a5eec71c71735c2f55a to your computer and use it in GitHub Desktop.
地址的对齐补齐
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
int main() { | |
char ch = 8; // 1 + 3 | |
int it = 9; // 4 + 4 | |
int* ptr = ⁢ // 8 | |
printf("%p\n%p\n%p\n\n", &ch, &it, &ptr); | |
typedef struct { | |
short sit; // 2 + 6 | |
double d; // 8 | |
char arr[9]; // 9 + 7 | |
int* ptr; // 8 | |
char ch; // 1 | |
}test; // 补齐+7 | |
test t; | |
printf("%p\n%p\n%p\n%p\n%p\n%d\n", &t.sit, &t.d, &t.arr, &t.ptr, &t.ch, sizeof(test)); | |
return 0; | |
} | |
/* | |
* 输出结果: | |
* 0x7ffe88dd928f | |
* 0x7ffe88dd9288 | |
* 0x7ffe88dd9280 | |
* | |
* 0x7ffe88dd9250 | |
* 0x7ffe88dd9258 | |
* 0x7ffe88dd9260 | |
* 0x7ffe88dd9270 | |
* 0x7ffe88dd9278 | |
* 48 | |
*/ | |
/* | |
* CPU为了寻址方便会对地址进行对齐和补齐 | |
* 对于32位处理器对齐补齐最大按4算(long、pointer), 因为32位有4根总线 | |
* 对于64位处理器对齐补齐最大按8算(long、pointer), 因为64位有8根总线 | |
* 其中对齐对于任意两个变量之间都存在, 而补齐主要是对struct而言, 保证struct数组内部能对齐 | |
* 栈中内存的分配是从高地址到低地址(intel处理器, amd是从低到高) | |
* 对于struct内部成员变量从低地址到高地址增长 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment