Search code examples
ccompiler-construction

Correct Return Values between normal and optimized builds


In slides 137-140 of this presentation, it was mentioned that bar() and maybe even foo() was compiled as inline functions for this sample program, resulting in the printout of a being 42 in normal builds even though it should technically be garbage. Do you happen to know why is the output garbage as expected when the optimizer kicks in?

I've included the source code

#include <stdio.h>
void foo(void)
{
    int a;
    printf("%d\n", a);
}
void bar(void)
{
    int a = 42;
}
int main(void)
{
    bar();
    foo();
    return 0;
}

and the command prompt printout for reference.

$ cc foo.c && ./a.out
42

$ cc -O foo.c && ./a.out
1606415608

Solution

  • Just an educated guess:

    In the non-optimized case the compiler reserves a space for the a variable in bar() and initializes it to 42. Then, when foo() is called, it uses the same space for the uninitialized a and prints out 42.

    When it's optimized, the initialization of a in bar() is optimized away, because it's not used. Probably, even the call to bar() is eliminated. So, as expected, foo() prints out garbage, that is whatever happens to be in that memory slot (or register) at the time.