Reputation: 175
I was playing around with pointers trying to manipulate the value of one var using the pointer to another var, based on how the local vars are typically stacked in a C program.
int i = 30;
int arr[4];
printf("%d\n", *(arr - 5)); // 30
int arr[4];
int i = 30;
printf("%d\n", *(arr - 5)); // also 30
I thought that the latter should print 30 for *(arr + 5)
, because that's how I thought the local vars are pushed onto the stack, but the vars seemed to be laid out in memory in the same manner. I'd like to understand what's happening here. Also, I'm assuming this is system/compiler dependent.
Upvotes: 1
Views: 120
Reputation: 14432
Short Answer: Memory layout (between different variables) is up to the compiler, and is implementation dependent.
Long Answer: The compiler can decide how to allocate memory to variables. While most compilers will allocate the memory sequentially, there is no guarantee. In particular, especially when optimizing, the compiler may be able to eliminate unused variables, or just placed them into registers.
Another factor is alignment. The compiler may decide to reorder variables to reduce the padding between variables.
Upvotes: 5
Reputation: 113
Accessing values beyond array bounds has undefined effects. In your case, the value you are getting is random and it just happens to be 30.
Upvotes: 0