In order to understand Buffer Overflow Vulnerabilities, i'm looking for some clarification around what the stack actually looks when you declare an array. For the following code:
int main()
{
int a = 0;
char b[8];
char c[8];
I understand that the stack will look like:
4 bytes a, 8 bytes b, 8 bytes c
but if the code instead is:
int main()
{
int a = 0;
int b[8];
char c[8]
What does the stack look like? I'm thinking that it will be 4 bytes a, then 32 (8*4) bytes b, and then 8 bytes for c. However, i'm not entirely sure how the indexing would work at that point (is it b[0] closest to a, or b[7]?).
Any clarification would help, thanks!
CodePudding user response:
First of all, you may not assume that any specific sequence will be used when placing variables on the stack. The compiler may choose the sequence. This happens often when optimizations are used. In this case the compiler may not allocate space on the stack until the first time the variable is referenced.
Additionally, the compiler may opt not to use the stack at all, if the variable is short-lived, and may store the variable in a CPU register instead.
In terms of how much memory is needed, it will depend on the system. Some systems may allow allocation of 8 bits at a time. Some systems may force everything to 32 bits of width. Some systems may add padding to make sure that larger width variables align properly.