使用C ++中的内联汇编在数组上循环

时间:2018-02-14 11:20:36

标签: c++ xcode assembly inline-assembly

Xcode生成EXC_BAD_ACCESS错误。 我想问题是我弄乱了访问数组的寄存器'值。

非常感谢平原一步一步的解释,谢谢!

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 < 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 > 0; digit *= 10)
        countingSort(array, length, digit); // Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
}

0 个答案:

没有答案