title: Variables shadowing in C - why compiler got confused?
body: <p>I have this code to parse JSON. The structure has a key, val and pointer to next structure. Due to nesting, the val pointer points sometimes to jss structure.</p>
  <p>The code below</p>
  <pre><code>struct jss {
      uint8_t type;
      char *key;
      char *val;
      struct jss *next;
  };
  
  void my_f() {
      ...
      struct jss *js = (struct jss *)malloc(sizeof(struct jss));
      ...
      while(js) {
          struct jss *js1 = (struct jss *)js-&gt;val;
          ...
      }
  }
  </code></pre>
  <p>compiles and runs fine and has this assembly:</p>
  <pre><code>struct jss *js = (struct jss *)malloc(sizeof(struct jss));
   4ea:   bf 20 00 00 00          mov    $0x20,%edi
   4ef:   e8 00 00 00 00          callq  4f4 &lt;Init+0x407&gt;
   4f4:   48 89 45 e8             mov    %rax,-0x18(%rbp)
   
      ...
      
          char *t, *f, *h;
          struct jss *js1 = ((struct jss *)(js-&gt;val));
   522:   48 8b 45 e8             mov    -0x18(%rbp),%rax
   526:   48 8b 40 10             mov    0x10(%rax),%rax
   52a:   48 89 45 b0             mov    %rax,-0x50(%rbp)
  </code></pre>
  <p>We see that rbp-0x18, which has the addr of js structure is moved to rax, rax then adds 0x10 to point
  to js-&gt;val address and the result is stored in rbp-0x50 which holds the js1. So far, so good!</p>
  <p>But if I change the code to this (js1 is replaced by js):</p>
  <pre><code>struct jss {
      uint8_t type;
      char *key;
      char *val;
      struct jss *next;
  };
  
  void my_f() {
      ...
      struct jss *js = (struct jss *)malloc(sizeof(struct jss));
      ...
      while(js) {
          char *t, *f, *h;
          struct jss *js = (struct jss *)js-&gt;val;
          ...
      }
  }
  </code></pre>
  <p>I have this assembly:</p>
  <pre><code>struct jss *js = (struct jss *)malloc(sizeof(struct jss));
       4ea:   bf 20 00 00 00          mov    $0x20,%edi
       4ef:   e8 00 00 00 00          callq  4f4 &lt;Init+0x407&gt;
       4f4:   48 89 45 e8             mov    %rax,-0x18(%rbp)
  
      ...
  
              char *t, *f, *h;
              struct jss *js = ((struct jss *)(js-&gt;val));
       522:   48 8b 45 c8             mov    -0x38(%rbp),%rax
       526:   48 8b 40 10             mov    0x10(%rax),%rax
       52a:   48 89 45 c8             mov    %rax,-0x38(%rbp)
  </code></pre>
  <p>Which compiles fine but segfaults:
  Instead of loading the address of js structure (rbp-0x18) into rax, the loaded address is that of the
  new structure I create...then there is no surprise why it segfaults.</p>
  <p>The question is what is illegal about the second code. I know about variable shadowing and this is indeed my intention. Why the compiler gets confused (I use gcc) ?</p>