0

I don't understand why when bar is called it writes to same stack location as "foo" for local variable?

Unsure why this does output

$ gcc -O 3 test.c -o mytest local foo is 10 local foo is 12

. Thanks

#include <stdio.h>

int foo(int initialize, int val)
{
    int local;

    if (initialize) {
        local = val;
    } else {
        printf("local foo is %d\n", local);
    }

}

int bar(int initialize, int val)
{
    int local;

    if (initialize) {
        local = val;
    } else {
        printf("local bar is %d\n", local);
    }

}

int main()
{
    foo(1, 10); //set to 10
    foo(0, 0); //print it
    bar(1, 12); //set to 12
    foo(0, 0); //print foo again

    return 0;
}
  • Why wouldn't it? Both of them aren't in scope at the same time and using the value of an uninitialized variable is undefined behavior. – Retired Ninja Jun 07 '23 at 02:03
  • 3
    [(Why) is using an uninitialized variable undefined behavior?](https://stackoverflow.com/questions/11962457/why-is-using-an-uninitialized-variable-undefined-behavior) and [Why does the C standard leave use of indeterminate variables undefined?](https://stackoverflow.com/questions/3248118/why-does-the-c-standard-leave-use-of-indeterminate-variables-undefined) are worth reading. – Retired Ninja Jun 07 '23 at 02:06
  • "Location"? You are printing an uninitialized value as a decimal (number). If you want the address it's `... "%p", (void *) &local)`. Your implementation probably uses a call stack and it's pretty natural that an (almost) identical function would end up storing variables at the same location. – Allan Wind Jun 07 '23 at 02:11
  • Also, you should refactor your two function into one by passing the the string that differ. – Allan Wind Jun 07 '23 at 02:13
  • You say `foo()` and `bar()` return an `int` but you don't have any return statement in either. – Allan Wind Jun 07 '23 at 02:20
  • @AllanWind Sorry, I meant print – MaliceAin'tIt Jun 07 '23 at 09:43
  • > Why wouldn't it? Both of them aren't in scope at the same time and using the value of an uninitialized variable is undefined behavior. @RetiredNinja Are you saying that this is just how gcc and clang do it? Since it is "undefined behavior" a compiler could do whatever it wants to? – MaliceAin'tIt Jun 07 '23 at 09:52

0 Answers0