Check below program,
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; }
In the above program, even though array size is 10, after the first array there is exactly 6 extra locations reserved in the stack (12bytes), I am wondering why this extra space got reserved? and this extra space size is varying for different size(Its not 12 for size 20). Can anybody explain the concept behind these allocations?
Output of above program using g++/gcc is,
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
Advertisement
Answer
You can’t expect the order that items will be allocated on the stack matches the order they are defined in code unless you explicitly specify a structure for how fields should be stored relative to each other. The compiler can and does reorder elements for performance or other reasons.
There is no way to tell for sure what those items are without checking the assembly to see how they get used. Reading them is undefined behavior since you can’t tell at compile time what they will be, or if they will even represent valid memory since it is outside of the bounds of any of the variables you defined. Odds are, they are just other variables in your program though.