Exercise using pointers in C give ambiguous output

This is the code of my teacher:

#include <stdio.h>
void foo1(int xval){
    int x;
    x = xval;
    printf("Address of x: %p\nValue of x: %d\n", &x, x);
void foo2(int dummy){
    int y;
    printf("Address of y: %p\nValue of y: %d\n", &y, y);
int main(void){
    return 0;

And this is the output generated:

screenshot of the output of the execution

Anyone can explain me why?



answered 1 week ago Soumen #1

stack after call                     stack after call 
to foo1()                            to foo2()
+----------------+                   +----------------+    |
| stack frame of |                   | stack frame of |    |
| main()         |                   | main()         |    v
++++++++++++++++++ <-- same addr --> ++++++++++++++++++   stack
| stack frame of |                   | stack frame of |   growth
| foo1()         |                   | foo2()         |
+----------------+                   +----------------+

Now the address of x in stack frame of foo1() is same as address of y in stack frame of foo2().

This is because both functions have same number and type of arguments and local variables (which are pushed onto stack). In call of foo1() the value in address of x (0x7fff63387a84 in your case) is set to 7. This value persists as there is no other function call between foo1() and foo2().

NOTE This answer is only for your understanding. You should not rely on the value of y as it is uninitialized (as pointed out in the previous comments). This is mere an accidental phenomena. I suggest you to go through how stack frames are formed.

comments powered by Disqus