I am trying to understand how C allocates memory on the stack. I always thought that variables on the stack can be represented as member variables of structs, they occupy a sequential, contiguous block of bytes on the stack. To help illustrate this problem, I found somewhere, I created this small program that reproduced this phenomenon.
#include <stdio.h> #include <stdlib.h> #include <string.h> void function(int *i) { int *_prev_int = (int *) ((long unsigned int) i - sizeof(int)) ; printf("%d\n", *_prev_int ); } void main(void) { int x = 152; int y = 234; function(&y); }
See what I do? Suppose sizeof(int) is 4: I am looking for 4 bytes behind the passed pointer, as this will read 4 bytes to where int y on the caller's stack.
It did not print 152. It is strange when I look at the following 4 bytes:
int *_prev_int = (int *) ((long unsigned int) i + sizeof(int)) ;
and now it works, prints everything in x inside the caller's stack. Why does x have a lower address than y ? Are stack variables overloaded?
source share