title: Segmentation fault: 11 With Array Assignment in Loop Using x86 GNU GAS Assembly
body: <p>This question is similar to another question I posted <a href="https://stackoverflow.com/questions/51255771/error-raised-when-attempting-to-assign-value-at-index-of-array-with-x86-assembly">here</a>. I am attempting to write the Assembly version of the following in <code>c/c++</code>:</p>
  
  <pre><code>int x[10];
  for (int i = 0; i &lt; 10; i++){
   x[i] = i;
  }
  </code></pre>
  
  <p>Essentially, creating an array storing the values <code>1</code> through <code>9</code>.</p>
  
  <p>My current logic is to create a label that loops up to <code>10</code> (calling itself until reaching the end value). In the label, I have placed the instructions to update the array at the current index of iteration. However, after compiling with <code>gcc filename.s</code> and running with <code>./a.out</code>, the error <code>Segmentation fault: 11</code> is printed to the console. My code is below:</p>
  
  <pre><code>.data
    x:.fill 10, 4
    index:.int 0
    end:.int 10
  
  .text
  .globl _main
  _main:
    pushq %rbp
    movq %rsp, %rbp
    subq $16, %rsp
    jmp outer_loop
    leave
    ret
  
  outer_loop:
   movl index(%rip), %eax;
   cmpl end(%rip), %eax
   jge end_loop
   lea x(%rip), %rdi;
   mov index(%rip), %rsi;
   movl index(%rip), %eax;
   movl %eax, (%rdi, %rsi, 4)
   incl index(%rip)
   jmp outer_loop
   leave
   ret
  
  end_loop:
    leave
    ret
  </code></pre>
  
  <p>Oddly the code below</p>
  
  <pre><code>lea x(%rip), %rdi;
  mov index(%rip), %rsi;
  movl index(%rip), %eax;
  movl %eax, (%rdi, %rsi, 4)
  </code></pre>
  
  <p>works only if it is not in a label that is called repetitively. Does anyone know how I can implement the code above in a loop, without <code>Segmentation fault: 11</code> being raised? I am using <code>x86</code> Assembly on MacOS with <code>GNU GAS</code> syntax compiled with <code>gcc</code>.</p>
  
  <p>Please note that this question is not a duplicate of <a href="https://stackoverflow.com/questions/8197647/assembly-x86-loop-segmentation-fault">this</a> question as different Assembly syntax is being used and the scope of the problem is different.</p>