title: Understanding Base Pointer and Stack Pointers: In Context with gcc Output
body: <p>I have the following C program:</p>
  
  <pre><code>int main()
  {
      int c[10] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2};
      return c[0];
  }
  </code></pre>
  
  <p>and when compiled using the -S directive with gcc I get the following assembly:</p>
  
  <pre><code>    .file   "array.c"
      .text
  .globl main
      .type   main, @function
  main:
  .LFB0:
      .cfi_startproc
      pushq   %rbp
      .cfi_def_cfa_offset 16
      .cfi_offset 6, -16
      movq    %rsp, %rbp
      .cfi_def_cfa_register 6
      movl    $0, -48(%rbp)
      movl    $0, -44(%rbp)
      movl    $0, -40(%rbp)
      movl    $0, -36(%rbp)
      movl    $0, -32(%rbp)
      movl    $0, -28(%rbp)
      movl    $0, -24(%rbp)
      movl    $0, -20(%rbp)
      movl    $1, -16(%rbp)
      movl    $2, -12(%rbp)
      movl    -48(%rbp), %eax
      leave
      .cfi_def_cfa 7, 8
      ret
      .cfi_endproc
  .LFE0:
      .size   main, .-main
      .ident  "GCC: (GNU) 4.4.5 20110214 (Red Hat 4.4.5-6)"
      .section        .note.GNU-stack,"",@progbits
  </code></pre>
  
  <p>What I do not understand is why are the earlier array elements further from the bp? It almost seems like the elements on the array are being placed in opposite order. </p>
  
  <p>Also why does gcc not use push instead of movl, to push the array elements onto the stack?</p>
  
  <hr>
  
  <p><strong>DIFFERENT VIEW</strong></p>
  
  <p>Moving the array to global namespace as a static variable to the module I get:</p>
  
  <pre><code>    .file   "array.c"
      .data
      .align 32
      .type   c, @object
      .size   c, 40
  c:
      .long   0
      .long   0
      .long   0
      .long   0
      .long   0
      .long   0
      .long   0
      .long   0
      .long   1
      .long   2
      .text
  .globl main
      .type   main, @function
  main:
  .LFB0:
      .cfi_startproc
      pushq   %rbp
      .cfi_def_cfa_offset 16
      .cfi_offset 6, -16
      movq    %rsp, %rbp
      .cfi_def_cfa_register 6
      movl    c(%rip), %eax
      leave
      .cfi_def_cfa 7, 8
      ret
      .cfi_endproc
  .LFE0:
      .size   main, .-main
      .ident  "GCC: (GNU) 4.4.5 20110214 (Red Hat 4.4.5-6)"
      .section    .note.GNU-stack,"",@progbits
  </code></pre>
  
  <p>Using the following C program:</p>
  
  <pre><code>static int c[10] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2};
  
  int main() 
  {
      return c[0];
  }
  </code></pre>
  
  <p>This doesn't give more insight to the stack. But it is intersting to see the differement output of assembly using slightly different semantics.</p>