title: On the difference between pointer and array notation when used with free()
body: <p>And, welcome back to another fabulous episode of 'Puny Mortals Asking <strike>(Potentially)</strike> Dumb Questions'.</p>
  
  <p>I wrote a solution to <a href="http://www.eng.uerj.br/~fariasol/disciplinas/LABPROG/C_language/Kernighan_and_Ritchie/solved-exercises/solved-exercises.html/krx116.html" rel="nofollow">K&amp;R's exercise 1-16</a> that uses dynamic memory allocation. As part of checking my work, I ran my code through Valgrind. Valgrind reported some memory leaks, though I had a 1:1 malloc:free ratio (which is perplexing).  After much fiddling and reading of the <a href="http://www.gnu.org/software/libc/manual/" rel="nofollow">GNU c lib manual</a> <em>and</em> the <a href="http://valgrind.org/docs/manual/manual.html" rel="nofollow">Valgrind user manual</a>, I eventually came to SO. None of the posts that I read really solved my problem, until I noticed some solutions to other unrelated problems that used a notation that may be expressed as the following equivalence:</p>
  
  <p><code>*(dbl_ptr + i) == dbl_ptr[i]</code></p>
  
  <p>Where <code>dbl_ptr</code> is of type <code>char**</code> and <code>i</code> is of type <code>int</code>.</p>
  
  <p>In my own, original code, I had been attempting to <code>free()</code> a double pointer in the following manner:</p>
  
  <pre><code>for( i = 0 ; i &lt; count ; ++i ) {
     free( (dbl_ptr + i) );     //Valgrind complains about a leak right here
  }
  
  free( dbl_ptr );
  </code></pre>
  
  <p>But when I recompile the program with these lines instead:</p>
  
  <pre><code>for( i = 0 ; i &lt; count ; ++i ) {
      free( dbl_ptr[i] );    //No more Valgrind complaints
  }
  
  free( dbl_ptr );
  </code></pre>
  
  <p>The program is then reported as being memory safe. Why?</p>
  
  <p>Help me to understand, merciful and benevolent StackOverlords!</p>
  
  <p><strong>CODA:</strong></p>
  
  <p>I recommend reading templatetypedef's answer to this post if you want a solid understanding of what happened here. I don't believe I can write a better explanation of what was going wrong within my own code. It turns out that my error was a combination of misunderstandings about how <code>free()</code> interprets arguments, as well as a fundamental ignorance of the semantics behind the array syntax in C.</p>
  
  <p>Fast and dirty: <code>dbl_ptr[i]</code> implicitly dereferences <code>dbl_ptr + i</code>.</p>