我在NASM写了一个冒泡排序程序。但它显示了分段错误。我试着生成以下c代码的汇编版本:
for(k=0;k<n;k++){
ptr=0;
while(ptr<=n-k){
if(data[ptr]>data[ptr+1])
do swap
ptr++;
}
}
以下NASM代码为:
section .data
msg db "%d"
four dd 4
msga db "%d ",0
section .bss
arr resd 8
section .text
global main
extern printf,scanf
main:
xor ecx,ecx
lp:
mov ebx,arr ;; from this line to jnz lp is using for taking 8 inputs
mov eax,ecx
mul dword[four]
add ebx,eax
pusha
push ebx
push msg
call scanf
add esp,8
popa
inc ecx
cmp ecx,8
jnz lp
mov ecx,0 ;; sorting replication of the above c program is starting
mov ebx,7 ;; outerloop will execute from 0 to 7
outerLoop:
mov eax,0 ;; it sets ptr=0
.innerLoop:
mov edx,8
sub edx,ecx
cmp eax,edx ;; its using for cheking ptr<=n-k
push ebx
push ecx
push edx
add esp,12
jle .task
pop edx
pop ecx
pop ebx
inc ecx
cmp ecx, ebx ;; its using for cheking whether k is in between 0 to 7
jl outerLoop
xor ecx,ecx
jmp lp1
.task:
mov ebx,dword[arr+eax*4] ;; its using to get data[ptr]
mov ecx,eax
push eax
add esp,4
add ecx,1
mov edx,dword[arr+ecx*4] ;; its using to get data[ptr+1]
cmp ebx,edx
jl .activity
xchg ebx,edx
mov dword[arr+eax*4],ebx
mov dword[arr+ecx*4],edx
.activity:
pop eax
pop edx
pop ecx
pop ebx
inc eax
jmp .innerLoop
lp1: ;; its using for print the output
mov ebx,arr
mov eax,ecx
mul dword[four]
add ebx,eax
pusha
push dword[ebx]
push msga
call printf
add esp,8
popa
inc ecx
cmp ecx,8
jne lp1
请问我帮我找出错误吗? 提前谢谢
答案 0 :(得分:0)
你为什么要尝试冒泡?从更容易的事情开始。跑步前走路。
看看内循环,你有:
push ebx
push ecx
push edx
add esp,12
jle .task
你将这3个寄存器压入堆栈并立即删除它们(你甚至没有将它们弹回各自的寄存器,所以不仅你的堆栈不平衡,你的寄存器包含错误的值)。现在你用add esp, 12
“清理了堆栈”,只要你有pop
s,堆栈就错了。