0
memory in C
#include <stdio.h> int main() { int a=3; int b [] = {1,2}; int c = 4; b[3]=10; printf ("a = %d",a); return 0; } output is a = 10; lifo rule, how compiller allocate memory?
1 Resposta
+ 2
It subtracts the stack pointer by a certain value to store local variables.
In this case the compiler allocates the variables at an offset of
a at 0x2C
b+0 at 0x20 and b+1 at 0x24
c at 0x28
By doing b+3 (b[3]) you get 0x20 + 4 * 3 = 0x2C which matches the variable a, so it overwrites a instead.
With optimizations enabled the compiler, in this case, loads 0x3 directly into the edx register of the cpu so there this doesn't happen.