title: Unable to understand a format string exploitation code
body: <p>I came across this code showing format string exploitation while reading <a href="http://www.loko.nu/formatstring/format_string.htm" rel="nofollow">this</a> article.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main(void)
  {
  char secret[]="hack.se is lame";
  char buffer[512];
  char target[512];
  
  printf("secret = %pn",&amp;secret);
  
  fgets(buffer,512,stdin);
  snprintf(target,512,buffer);
  printf("%s",target);
  }
  </code></pre>
  
  <p>Executing it with following input</p>
  
  <pre><code>[root@knark]$ ./a.out
  secret = 0xbffffc68
  AAAA%x %x %x %x %x %x %x //Input given
  AAAA4013fe20 0 0 0 41414141 33313034 30326566
  - [root@knark]$ 
  </code></pre>
  
  <p>What I understand till now is the sequence of <code>%x</code>'s will keep on printing the values at addresses above current <code>%esp</code> (I'm assuming that stack is growing downwards towards lower address). </p>
  
  <p>What I'm unable to understand is the input given is stored in <code>buffer</code> array which can't be less than 512 bytes away from current <code>%esp</code>. So, how can the output contain <code>41414141</code> (the hex representation of <code>AAAA</code>) just after the 4 <code>%x</code>, i.e, just above the 4 addresses of current <code>%esp</code>. I tried hard to stare at assembly code too but I think I couldn't follow the manipulation of strings on stack.</p>