最近学习内存分布,通过gdb调试发现一些问题,栈空间变量地址应该是从高往低分布的,但是调试发现地址虽然是从高往低分布,但是变量地址的顺序是乱的,请教同事他说可能是gcc/g++默认启用了堆栈保护,关于堆栈保护可以查看这篇文章https://www.ibm.com/developerworks/cn/linux/l-cn-gccstack/

#include <stdio.h>
int main()
{
    char a = 'a';
    char b = 'b';
    int i = 20;

    return 0;
}

默认编译

gcc -g test.c -o test
gdb test
(gdb) p $rsp
$1 = (void *) 0x7fffffffdde0
(gdb) p &a
$2 = 0x7fffffffddda "ab\024"
(gdb) p &b
$3 = 0x7fffffffdddb "b\024"
(gdb) p &i
$4 = (int *) 0x7fffffffdddc

关闭堆栈保护编译

g++ -g -fno-stack-protector test.c -o test
gdb test
(gdb) p $rsp
$1 = (void *) 0x7fffffffdde0
(gdb) p &a
$2 = 0x7fffffffdddf "a FUUUU"
(gdb) p &b
$3 = 0x7fffffffddde "ba FUUUU"
(gdb) p &i
$4 = (int *) 0x7fffffffddd8
(gdb) p $rsp - (void*)&i
$5 = 8
12-23 11:11