title: Looping over array using inline assembly inside C++
body: <p>Xcode generates an EXC_BAD_ACCESS error.
  I suppose the problem is that I messed up with the registers accessing arrays' values.</p>
  
  <p>Plain step-by-step explanation would be much appreciated, thanks!</p>
  
  <pre><code>void countingSort(int array[], int length, int digit) {
      int i, count[10] = { };
      int sorted[length];
  
      // Store number of occurrences in count[].
      // for (i = 0; i &lt; length; i++)
      //     count[ (array[i] / digit) % 10 ]++;
  
      // Inline assembler loop
      // in place of commented out for loop.
      asm(
          "loopOne: \n\t"
              "movl $0, %%ecx \n\t"
              "cmpl %%ecx, (%[length]) \n\t"
              "je loopTwo \n\t"
  
              "movl %[array], %%esp \n\t"
              "movl (%%esp, %%ecx, 4), %%eax \n\t"
              "movl (%[digit]), %%ebx \n\t"
              "divl %%ebx \n\t"
  
              "movl %[count], %%ebp \n\t"
              "movl (%%ebp, %%edx, 4), %%esi \n\t"
              "inc %%esi \n\t"
  
              "inc %%ecx \n\t"
              "jmp loopOne \n\t"
  
          "loopTwo: \n\t"
          // ...
  
          : [array] "=g" (array), [count] "=g" (count)
          : [digit] "r" ((long) digit), [length] "r" ((long) length)
      );
  }
  
  void radixSort(int array[], int length) {
      // Maximum number helps later when counting number of digits.
      int max = findMax(array, length);
  
      // Do Counting sort for every digit.
      for (int digit = 1; max / digit &gt; 0; digit *= 10)
          countingSort(array, length, digit); // Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
  }
  </code></pre>