4

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.

Manish Giri
  • 3,562
  • 8
  • 45
  • 81
  • Functions local variables go to stack. Also, function local variables only exist while function is executing, they go out of scope and disappear when function returns. Learn how stack works, and you should have your answer... – hyde Jun 09 '14 at 04:03
  • http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope also hv a look @ http://stackoverflow.com/questions/18250547/why-does-local-variable-value-still-exist-when-control-comes-out-of-function – vinay hunachyal Jun 09 '14 at 04:07

7 Answers7

4

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
3

The reason is that those variables are located on the call stack, and the same memory location is reused for subsequent calls. To get the behavior I think you're looking for, declare both variables in a single function and put the output statements alongside them instead of in another scope.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
1

Most compilers allocate local variables on the stack while inside a function.

When the function returns, the memory is returned to the system, and another function is free to reuse the memory for another local variable.

What happens here is in other words that foo1 allocates memory for x, but when it returns, the memory is returned to the system since x is no longer used.

The same memory address is then reused in foo2 to store y.

Note that memory on the stack is not allocated using malloc, the stack pointer is basically just a pointer that is moved around automatically as functions are entered and exited.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
0

void foo1(int xval) and void foo2(int dummy) are two different functions, so when one function is running, only that function's variables reside in stack. As soon as you call another function or return from function, local variable of that function present in stack. So, two variables of different function can have same address (but at different times).

Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137
0

Look at the difference between 'static' and 'automatic' memory allocation. You are using automatic memory allocation in function declarations and the memory is freed when the function is exited:

Automatic allocation happens when you declare an automatic variable, such as a function argument or a local variable. The space for an automatic variable is allocated when the compound statement containing the declaration is entered, and is freed when that compound statement is exited. In GNU C, the size of the automatic storage can be an expression that varies. In other C implementations, it must be a constant.

Bottom-line. After foo1(7) exits, the same memory is used for 7 is reused for 11 in foo2(11).

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

As you must have read by now about the storage classes, try relating that here. Here the storage class in action is the automatic.

main --> foo1 --> allocate x --> do the work in foo1 --> free the memory location used by x --> call foo2 , then repeat for y what was done for x (here it'll use the same memory location which was freed of x).

This is not because you have not used pointers. You may want to (you should try) use pointers as well like below , but expect same result again:

#include <stdio.h>
void foo1(int xval) 
{ 
 int *x; 
 x = &xval; 
 /* print the address and value of x here */ 
 printf("\n Address of variable pointed by 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; 
} 
Diwakar Sharma
  • 415
  • 1
  • 9
  • 26
0

you may be looking for this:

 main()                                                           
   {
       char   a;                                                    
       int    x;                                                    
       float  p, q;                                                 

       a  = 'A';                                                    
       x  = 125;                                                    
       p  = 10.25, q = 18.76;                                       
       printf("%c is stored at addr %u.\n", a, &a);                 
       printf("%d is stored at addr %u.\n", x, &x);                 
       printf("%f is stored at addr %u.\n", p, &p);                
       printf("%f is stored at addr %u.\n", q, &q);                 

       }

or

// Declare and initialize an int variable

int var = 34;

// Declare a pointer to int variable

int *ptr;

// Initialize ptr to point to variable var

ptr = &var;



// Access var directly and indirectly

printf("\nDirect access, variable var value = var = %d", var);

// you can use %p for the pointer memory address directly or

// %0x or %0X or %p in hexadecimal representative instead of

// %d, just to avoid confusion here

printf("\nIndirect access, variable var value = *ptr = %d", *ptr);

// Display the address of var two ways

printf("\n\nThe memory address of variable var = &var = %p", &var);

printf("\nThe memory address of variable var = ptr = %p\n", ptr);
Foggymist
  • 1
  • 1