我目前正在尝试学习汇编,我正在尝试使用该语言实现基本的排序算法。我想我已经掌握了它的逻辑,但这也可能是错误的。无论哪种情况,每当我尝试执行选择排序的交换部分时,都会以访问冲突错误告终。根据我所看到的关于这个主题的其他一些问题,我实现交换的方式是有效的(但是,如果我错了,请再次纠正我)。在任何情况下,假设交换是正确的,是什么导致了访问冲突?
代码如下:
int _tmain(int argc, _TCHAR* argv[])
{
char * arr;
arr = new char[5];
arr[0] = '2';
arr[1] = '5';
arr[2] = '1';
arr[3] = '3';
arr[4] = '4';
int len = 5;
__asm{
push eax
push ebx
push ecx
push edx
push esi
push edi
mov eax, 0; //i
mov ebx, 0; //j
mov ecx, arr; //the array
mov edx, 0; //min
mov esi, len; //array length
mov edi, len; //array len - 1
sub edi, 1;
mov dl, 0;
mov dh, 0;
OUTERLOOP:
cmp eax, edi;
jge END_OUTER;
mov ebx, eax;
add ebx, 1;
mov edx, eax;
INNERLOOP:
cmp ebx, esi;
jge END_INNER;
mov al, byte ptr[ecx+ebx*1];
mov bl, byte ptr[ecx+edx*1];
cmp al, bl;
jl LESS;
jge GREATER;
LESS:
mov edx, ebx;
inc ebx;
jmp INNERLOOP;
GREATER:
inc ebx;
jmp INNERLOOP;
END_INNER:
cmp edx, eax;
je PASS;
jne SWAP;
PASS:
inc eax;
jmp OUTERLOOP;
SWAP:
mov dh, [ecx+eax];
mov dl, [ecx+edx];
mov[ecx+eax], dl;
mov[ecx+edx], dh;
inc eax;
jmp OUTERLOOP;
END_OUTER:
pop edi
pop esi
pop edx
pop ecx
pop ebx
pop eax
}
for(int i = 0; i < len; i++)
{
printf("%cn", arr[i]);
}
return 0;
}
我得到的错误消息如下:
First-chance exception at 0x012f1474 in Clean2.exe: 0xC0000005: Access violation reading location 0x004e67c8.
Unhandled exception at 0x012f1474 in Clean2.exe: 0xC0000005: Access violation reading location 0x004e67c8.
请多多指教,谢谢。
编辑:我已经改变了我的代码,并试图使用xchg似乎做的伎俩。我从下面的答案中得到了建议,并决定将我将用于字节的寄存器分开。在这一点上,我不再得到任何错误。这是更新后的代码
int _tmain(int argc, _TCHAR* argv[])
{
char temp;
char * arr;
arr = new char[5];
arr[0] = '2';
arr[1] = '5';
arr[2] = '1';
arr[3] = '3';
arr[4] = '4';
int len = 5;
__asm{
push eax
push ebx
push ecx
push edx
push esi
push edi
mov ebx, arr; //array
mov ecx, 0; //i
mov edx, 0; //j
mov esi, 0; //min
mov edi, len; //length
OUTERLOOP:
cmp ecx, edi;
jge END_OUTER;
mov edx, ecx;
add edx, 1;
mov esi, ecx;
INNERLOOP:
cmp edx, edi;
jge END_INNER;
mov ah, byte ptr[ebx + edx];
mov al, byte ptr[ebx + esi];
cmp ah, al;
jl LESS;
jge GREATER;
LESS:
mov esi, edx;
inc edx;
jmp INNERLOOP;
GREATER:
inc edx;
jmp INNERLOOP;
END_INNER:
cmp esi, ecx;
je PASS;
jne SWAP;
PASS:
inc ecx;
jmp OUTERLOOP;
SWAP:
xchg al, [ebx + ecx];
inc ecx;
jmp OUTERLOOP;
END_OUTER:
pop edi
pop esi
pop edx
pop ecx
pop ebx
pop eax
}
for(int i = 0; i < len; i++)
{
printf("%cn", arr[i]);
}
return 0;
}
但是现在我在数组中得到的是1,1,1,3,4而不是1,2,3,4,5。我会继续努力解决这个问题。如果有人能看出哪里不对,请告诉我。谢谢你。
首先,看起来您正在使用eax
寄存器进行多个操作。注意,字节大小的寄存器al
与eax
共享存储空间。具体来说,当您执行mov al, ...
时,您将覆盖eax
中值的低8位。