title: Buffer overflow in C
body: <p>I'm attempting to write a simple buffer overflow using C on Mac OS X 10.6 64-bit. Here's the concept:</p>
  
  <pre><code>void function() {
      char buffer[64];
      buffer[offset] += 7;    // i'm not sure how large offset needs to be, or if
                              // 7 is correct.
  }
  
  int main() {
  
      int x = 0;
      function();
      x += 1;
      printf("%d\n", x);      // the idea is to modify the return address so that
                              // the x += 1 expression is not executed and 0 gets
                              // printed
  
      return 0;
  }
  </code></pre>
  
  <p>Here's part of main's assembler dump:</p>
  
  <pre><code>...
  0x0000000100000ebe &lt;main+30&gt;:   callq  0x100000e30 &lt;function&gt;
  0x0000000100000ec3 &lt;main+35&gt;:   movl   $0x1,-0x8(%rbp)
  0x0000000100000eca &lt;main+42&gt;:   mov    -0x8(%rbp),%esi
  0x0000000100000ecd &lt;main+45&gt;:   xor    %al,%al
  0x0000000100000ecf &lt;main+47&gt;:   lea    0x56(%rip),%rdi        # 0x100000f2c
  0x0000000100000ed6 &lt;main+54&gt;:   callq  0x100000ef4 &lt;dyld_stub_printf&gt;
  ...
  </code></pre>
  
  <p>I want to jump over the <code>movl</code> instruction, which would mean I'd need to increment the return address by 42 - 35 = 7 (correct?). Now I need to know where the return address is stored so I can calculate the correct offset.</p>
  
  <p>I have tried searching for the correct value manually, but either 1 gets printed or I get <code>abort trap</code> – is there maybe some kind of buffer overflow protection going on?</p>
  
  <hr>
  
  <p>Using an offset of 88 works on my machine. I used Nemo's approach of finding out the return address.</p>