title: Variables and allocation inside of a loop
body: <p>Recently I stumbled upon source code where programmer declared variables inside one infinite loop depending on <em>if/else</em> conditions. What I found odd is that the code ran and it didn't implied any memory leaks. First I thought that maybe it was architecture specific thing (the code was for ARM) but I ran some tests and I found out that binaries on IA32 compiled with GCC acted in same way.</p>
  
  <p>My approach was like this: I've created two small program foo.c and bar.c</p>
  
  <p>Foo.c:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main(void)
  {
     int i;
  
     for(i=0; i&lt;10; i++) {
        char buf[10];
        buf[i] = 0;
        printf("buf[%d] (@ %#x) == %d\n", i, &amp;buf, buf[i]);
     }
  
     return(0);
  }
  </code></pre>
  
  <p>Bar.c:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main(void)
  {
     int i;
  
     for(i=0; i&lt;10; i++) {
        char *ptr;
        ptr = (char *) malloc(10);
        ptr[i] = 0;
        printf("buf[%d] (@ %#x) == %d\n", i, &amp;ptr, ptr[i]);
     }
  
     return(0);
  }
  </code></pre>
  
  <p>The reason behind making explicit distinction between declaring an array in <em>Foo.c</em> and allocating memory in <em>Bar.c</em> was that first I thought that maybe compiler auto-magically detects that it's the same variable and just ignoring the declaration after initial <em>for</em> iteration which of course shouldn't be the case in <em>Bar.c</em> because I explicitly allocate the memory.</p>
  
  <p>What was really weird to me that in both examples the address of both an array and allocated memory stays the same after initial <em>for</em> iteration.</p>
  
  <p>I do not completely understand that and I don't have my copy of <em>K&amp;R</em> with me so I'll be thankful for an explanation. (Also if I made any mistake in my reasoning I'd be glad for pointing it out.)</p>