gpt4 book ai didi

c - 如何修复选择排序交换访问冲突

转载 作者:行者123 更新时间:2023-11-30 15:31:15 24 4
gpt4 key购买 nike

我目前正在尝试学习汇编,并尝试使用该语言实现基本的排序算法。我想我已经明白了它的逻辑,但这也可能是错误的。无论哪种情况,每当我尝试执行选择排序的交换部分时,我都会遇到访问冲突错误。根据我所看到的有关该主题的一些其他问题,我实现交换的方式是有效的(但再次,如果我错了,请纠正我)。无论如何,假设交换是正确的,是什么导致了我的访问冲突?

这是代码:

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("%c\n", 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("%c\n", arr[i]);
}
return 0;
}

但是现在我的数组中得到的是 1, 1, 1, 3, 4,而不是 1, 2, 3, 4, 5。我将继续努力解决这个问题。如果有人能看出问题所在,请告诉我。谢谢。

最佳答案

一方面,您似乎正在将 eax 寄存器用于多种用途。请注意,字节大小的寄存器 aleax 共享存储。具体来说,当您执行 mov al, ... 时,您会覆盖 eax 中的值的低 8 位。

关于c - 如何修复选择排序交换访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24943297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com