Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two integer variables residing at one memory address?

Tags:

c

pointers

memory

I am learning pointers in C, and am trying to solve exercises on pointers available online. Although the below question doesn't make use of pointers, I understand that the incorrect output is due to lack of usage of pointers. Here is the question-

/* p2.c 
Find out (add code to print out) the address of the variable x in foo1, and the 
variable y in foo2. What do you notice? Can you explain this? 
*/

And here is my answer-

#include <stdio.h>
void foo1(int xval) 
{ 
 int x; 
 x = xval; 
 /* print the address and value of x here */ 
 printf("\n Address of variable x is:%p\n", &x);
 printf("\n Value of variable x is: %d\n", x); 

} 
void foo2(int dummy) 
{ 
 int y;
 y=dummy; 
 /* print the address and value of y here */ 
 printf("\n Address of variable y is:%p\n", &y);
 printf("\n Value of variable y is: %d\n", y); 
} 

int main() 
{ 
 foo1(7); 
 foo2(11); 

 return 0; 
} 

The output when compiling the program is-

 Address of variable x is:0x7fff558fcb98

 Value of variable x is: 7

 Address of variable y is:0x7fff558fcb98

 Value of variable y is: 11

From what I understand, when the program runs, and foo1 with an integer as function argument is called, the integer 7 is taken and stored in the integer variable x. The function foo1 then prints the address and value of variable x. Same thing repeats with function foo2.

But, I couldn't understand how is it that two integer variables with different values are residing at the same memory address 0x7fff558fcb98? Is it because of memory management issues in C (malloc, free etc-I'm not there yet!)?

Any help would be highly appreciated. Thank You.

like image 860
Manish Giri Avatar asked Feb 12 '23 18:02

Manish Giri


1 Answers

It's useful to visualize the state of the stack to understand the behavior. When you are in main, let's say the stack looks like:

enter image description here

When you enter foo1, the stack frame for foo1 is added to the stack and it looks like:

enter image description here

When you return from foo1, the stack will revert to:

enter image description here

When you enter foo2, the stack frame for foo2 is added to the stack and it looks like:

enter image description here

The state of the stack frame looks very similar for foo1 and foo2. It's not surprising that the addresses of the local variables x and y are identical.

Had the number of arguments, the arguments types or the local variable types been different, you would have noticed different values for the addresses of the local variables.

like image 55
R Sahu Avatar answered Feb 15 '23 10:02

R Sahu