Skip to content
Advertisement

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

Check below program,

JavaScript

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,

JavaScript

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement