I had a question regarding a C code.
#include <stdio.h>
void foo(void){
int a;
printf("%d\n",a);
}
void bar(void){
int a = 42;
}
int main(void){
bar();foo();
}
Apparently I am supposed to get a 42 as a result at the end of compilation. http://www.slideshare.net/olvemaudal/deep-c , slide #126. But when I compile it on my machine I get garbage values (gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu5))
Do I need to turn off some optimization? Or is the author of the slide wrong about this? Can someone explain what should be the result of the code? If it is 42, could you also explain how/why? Also, would the result be any different on a C++ compiler (g++).
Accessing uninitialized variables is simply undefined behavior.
Undefined behavior means that the standard doesn’t specify how to behave in some situations, including this one. The compiler might even “make demons fly out of your nose” (popular joke about UB 🙂 )
In that article the program works because
bar‘saandfoo‘saare placed in the same memory location, but this is completely uninsured and you should never rely on such behaviors!