title: Assembly segmentation fault ( array )
body: <p>beginner in assembly here (IA-32 assembly). I keep getting a seg fault when compiling in gcc, I'm guessing its attempting to access forbidden memory, but I can't pin point it down. The task was to find the greatest common denominator of an array. I figured implementing this via an array with a side function gcd (returns the gcd of 2 numbers). Here is the code:</p>
  
  <pre><code>.intel_syntax noprefix 
  
  .text
  
  .global GCD
  
  GCD:
  
  push edi
  push esi
  
  
  mov edi, [ebp + 12] # number of elements in the array
  mov esi, [ebp + 8] #array address 
  
  mov eax, [esi] # place the first element of the array into eax
  mov ecx, 1 # set the counter to 1
  
  next_number: #accumulating the gcd of the entire array
  
  cmp ecx, edi #if the counter reaches the max number of elements,
  ja end       #end the the loop
  
  
  push [esi + 4*ecx] #calling the gcd function, pushing the numbers on the 
  push eax           #stack, so gcd can pick them up
  call gcd 
  add esp, 8
  
  
  inc ecx            #increment the counter
  
  jmp next_number    #next iteration
  
  
  end:
  
  
    pop esi 
    pop edi 
    leave 
    ret
  </code></pre>
  
  <p>And the gcd side function:  </p>
  
  <pre><code># The C algorithm for finding the gcd of 2 numbers implemented in IA-32
  #   while(y)
  #   {
  #     r = x % y;
  #     x = y;
  #     y = r;
  #   }
  #   return x;
  
  .intel_syntax noprefix
  
  .text
  
  
  .global gcd
  
  gcd:
  
  enter 0,0
  
  mov eax, [ebp + 8]
  mov ecx, [ebp + 12]
  
  loop:
  
  cmp ecx, 0
  je end
  
  xor edx, edx
  idiv ecx
  
  mov eax, ecx
  mov ecx, edx
  
  jmp loop
  
  
  end:
  
  leave
  ret
  </code></pre>