0
void foo()
{
    int i;
    printf("%d",i++);
}

int main()
{
    int j;
    for(j=0;j<10;j++)
    {
        foo();
    }
}

The output of the code is a series of 10 random but continuous numbers. I wanted to know how is this possible if i is being initialized each time and my storage class is also auto?
Also is the stack frame for foo() assigned again every time it is called or is it the same one?

Sunny
  • 51
  • 1
  • 7

1 Answers1

0

auto variables are not automatically initialized, they contain garbage. Those variables are allocated typically in the stack, with a quick stack operation. In foo(), you have such a variable, so the printf outputs random data.

Even if the function foo() was called recursively, the auto-variables problem stays there, every call makes a new stack frame containing garbage.

So,

Is the stack frame of a function called multiple times different each time?

YES. Unless you use static variables in that function. But then, you will have variables which keep their value, but which are in reality always the same (no more "local", or better, global but only visible in that function (scope)).

======== EDIT after comment ========
Well, the above sentence contains a formal error. It is not true that the stack frame will be different: it can be the same between calls (probably not if recursion is used). But, you can not be sure it is the same, so you must assume it is different each time. By assuming it is different, you state it is different, even if it is not true. Unless you want to exploit some arcane algorithm...

user3386109
  • 34,287
  • 7
  • 49
  • 68
  • Re β€œYES”: This is incorrect. The stack frame **may** vary between different calls, because the C standard does not require that it (notably: the state of uninitialized objects) be the same. But it is wrong to say that it **is** different each time. That can lead people to incorrect beliefs and expectations. In successive calls, it is not uncommon for the stack to be the same, as nothing may have acted to change it between calls. Furthermore, it cannot truly be different each time because there are a finite number of states available, so there must, in theory, be repetition eventually. – Eric Postpischil Nov 24 '19 at 11:21