为什么本地数组末尾有额外的空位置(c/c++/gcc)?

why does the local array has extra empty location at the end(c/c++/gcc)?

检查下面的程序,

int main()
{
    short int data1[]={1,2,3,4,5,6,7,8,9,10};
    short int data2[]={1,2,3,4,5,6,7,8,9,10};
    short int *ptr = data1;
    cout<<"data1 start addr = "<<data1<<endl;
    cout<<"data2 start addr = "<<data2<<endl;
    for (int i=0;i<20;i++, ptr++)
        cout <<"Data = "<<*ptr<<" Addr = "<<ptr<<endl;
    return 0;
}

在上面的程序中,尽管数组大小是 10,但在第一个数组之后 堆栈中保留了正好 6 个额外的位置(12 字节), 我想知道为什么会这样extra space 被保留了?这个额外的 space 尺码因尺码不同而异(尺码 20 不是 12)。 谁能解释一下这些分配背后的概念?

上述程序使用 g++/gcc 的输出是,

data1 start addr = 0x7ffc87350920
data2 start addr = 0x7ffc87350940
Data = 1 Addr = 0x7ffc87350920
Data = 2 Addr = 0x7ffc87350922
Data = 3 Addr = 0x7ffc87350924
Data = 4 Addr = 0x7ffc87350926
Data = 5 Addr = 0x7ffc87350928
Data = 6 Addr = 0x7ffc8735092a
Data = 7 Addr = 0x7ffc8735092c
Data = 8 Addr = 0x7ffc8735092e
Data = 9 Addr = 0x7ffc87350930
Data = 10 Addr = 0x7ffc87350932
Data = 32629 Addr = 0x7ffc87350934
Data = 0 Addr = 0x7ffc87350936
Data = 9232 Addr = 0x7ffc87350938
Data = 12176 Addr = 0x7ffc8735093a
Data = 22064 Addr = 0x7ffc8735093c
Data = 0 Addr = 0x7ffc8735093e
Data = 1 Addr = 0x7ffc87350940
Data = 2 Addr = 0x7ffc87350942
Data = 3 Addr = 0x7ffc87350944
Data = 4 Addr = 0x7ffc87350946

您不能指望项目在堆栈上的分配顺序与它们在代码中定义的顺序相匹配,除非您明确指定一个结构来说明字段之间的存储方式。出于性能或其他原因,编译器可以并且确实会重新排序元素。

如果不检查程序集以了解它们是如何使用的,就无法确定这些项目是什么。读取它们是未定义的行为,因为您无法在编译时判断它们将是什么,或者它们是否代表有效内存,因为它超出了您定义的任何变量的范围。很可能,它们只是您程序中的其他变量。