-1

This is a very small program which I wrote last night:

void testWithFunction(int val) {
  int someA;
  printf ("SomeA: %x %d \n ", &someA, someA);
  someA = val;    
}

int main() {
 int j = 5;
 while ( j-- ) {
    int i;
    if ( j == 4) { i = 10; }
    printf("i: %x %d \n", &i, i);   

 }

  testWithFunction(5);
  testWithFunction(10);
  testWithFunction(0);
  // system("pause");
  return 0;  
}

The output to the above was:

i: 28ff20 10
i: 28ff20 10
i: 28ff20 10
i: 28ff20 10
i: 28ff20 10
SomeA: fffffffe 2686916
SomeA: 5 2686916
SomeA: a 2686916

I used to think that variables declared inside loops had local scope - they were destroyed when the loop terminate. For each new iteration, all its local variables would be created again. However with this example, it seems that the same variable is reused each time and so, the variable can even remember its last written value. The same applies for functions - Variables local to a function should be destroyed when the function terminates and should be re-created when the function is called again! However, the results suggest that the variables behave as if they are declared with the static keyword! This is something new to me. Please correct me - Is the static keyword implicit for all variables??

I have tried the same thing with structure type nodes and found the same result. So I dont think we should assume that the variables are re-allocated to the same memory space and hence they retain their value. ( I agree "destroy" doesnt actually deletes the old value)

Example 2:

#include <stdio.h>  
typedef struct node    
{  
    int val;  
    struct node *next;  
}node;  

int main()  
{  
 int i;  
 node newtemp,root,temp;  

 scanf("%d",&i);  
 while(i--)  
 {  
     node array[i];  
     node n;  

     int j;  
     for(j = 0; j < i; j++) {   
            printf (" array: %x  ", &array[j] );                  
       }  


     n.val = i;  
     n.next = NULL;  
     printf("node: %x\n", &n);  

 }  
return 0;  
}  

Output:
4
array: 28feb0 array: 28feb8 array: 28fec0 node: 28ff00
array: 28fec0 array: 28fec8 node: 28ff00
array: 28fec0 node: 28ff00
node: 28ff00

letsc
  • 2,075
  • 5
  • 24
  • 43
  • possible duplicate of [When will memory used in a function become free ??(C programming)](http://stackoverflow.com/questions/7579069/when-will-memory-used-in-a-function-become-free-c-programming) – Goz Oct 12 '11 at 21:34
  • possible duplicate of [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Dour High Arch Oct 12 '11 at 21:35
  • 1
    Investigating this while writing C source code is kind of like poking a beehive with a stick while blindfolded. You're too far from what is *actually* going on. If you want to find out how the memory is laid out while your program is running, **use a debugger**. You can then see exactly what goes where, without having to guess from the other side of the compiler. – Greg Hewgill Oct 12 '11 at 21:52
  • My posted link on stack frames still fits your problem well. I truly suggest learning all bout stack frames. Then read about what odd things the compiler can do to explain why you can't rely on this sort of behaviour. – Goz Oct 12 '11 at 21:56

4 Answers4

2

What you have here is a classic case of undefined behaviour.

When will memory used in a function become free ??(C programming)

Edit: Your edit still shows undefined behaviour. Read up on stack frames carefully. The issue you are suffering comes about due to the fact that the stack frame within the loop is of identical size to the previous run through the loop. Therefore n always take up the same space in the stack. Never rely on behaviour like this, primarily because its undefined. Equally the compiler is free to optimise this in all sorts of fun ways that could, and probably will, thoroughly break your code.

Community
  • 1
  • 1
Goz
  • 61,365
  • 24
  • 124
  • 204
  • Which is the UB here?? I am just trying to create new stack variables inside a loop and I am just printing their addresses. I still couldnot get you how is the "stack frame within the loop is of identical size to the previous run through the loop" - the size is proportional to i which is decremented on each iteration – letsc Oct 12 '11 at 22:14
  • UB here is reading a variable that has not been initialized. Don't. – David Heffernan Oct 12 '11 at 22:22
2

You didn't initialize the local variable someA before you used it. It's Undefined Behaviour. Anything goes.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • That was done with a purpose - had i initialised someA, I couldnot say that someA somehow retained the last value it was assigned.. – letsc Oct 12 '11 at 21:56
  • 1
    Answer is just the same. It may retain a value. Or it may not. Or the program is at liberty to reformat your disk. Or sing La Marseillaise. You can't reason about UB. – David Heffernan Oct 12 '11 at 21:58
2

It's more along the lines of your code is basically just doing the same thing over again. Each time testWithFunction() is called, it allocates some space on the stack for the someA int. By chance, you always get the SAME chunk of stack space, so it appears that your variable is static. but it's just a random chance side effect.

If you'd called another function or did ANYTHING that affects the stack, you'd see the values randomly changing.

Marc B
  • 356,200
  • 43
  • 426
  • 500
1

printf ("SomeA: %x %d \n ", someA); has a bug,

you are printing two values but only supplying one. It's likely that the previous value just happens to be on the stack just after someA so printf reads it.

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263