Search code examples
ccompiler-constructionundefined

Undefined variable and the compiler optimization


I have a question about undefined variable and the demonstrated snipped code in down below:

After func_1() --- it will push A into the stack and set the value of that memory into 40 and then pop A out of the stack.

After func_2() --- it will push A into the stack again and inherit the value set before and the print out value will be 40.

void func_1()
{ int A = 40;}

void func_2()
{ int A; printf("%d/n",A);}

void main (void)
{
  func_1();
  func_2();
}

If we change the name A in func_2() into B to test the use of stack, and put extra code in it to test the use of the pool of named variables:

int A; printf("%d\n", A);

On my computer, it says B is 40, A is 0.

What I was wondering is, if the compiler has a pool of named variables that it reuses to help it optimize the compiled code(?), then why did I get a 0 on A? When is the compiler use the pool?

My question is based on this slide : http://www.slideshare.net/olvemaudal/deep-c/131-I_am_now_going_to


Solution

  • Most likely the variable A in the function func_2(); is allocated in the same stack position that the value 40 was (in the func_1()). Since you have not initialized the variable in the func_2() it will print the variable with a random value that it is in memory in this case 40 (because it was never overridden). It is similar to the scenario when the users free a pointer and then claim that they are able too see its content afterwards, although they may or may not see that value the behaviour is considered to be undefined. Needless to say that you should not rely on such behavior!

    I have made a simple test, to prove that it has nothing to do with the variables' names:

    void func_1()
    { 
        int A = 40; 
        int B = 10;
        printf("Memory A = %p Memory B = %p\n",&A, &B);
    }
    
    void func_2()
    { int B; printf("B = %d Memory B = %p\n",B, &B);}
    
    void main (void)
    {
      func_1();
      
      func_2();
      printf("\n");
    }
    

    output:

    Memory A = 0x7fff58f86b5c Memory B = 0x7fff58f86b58
    B = 40 Memory B = 0x7fff58f86b5c
    

    As you can see although B = 10 in func_1() in func_2()the print value was 40. why? if you check the memory address of the variable A in func_1() is 0x7fff58f86b5c the same memory address occupied by the variable Bin func_2().