-3

我在 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

你能帮我找出我的错误吗?提前谢谢

4

1 回答 1

0

你为什么要进行冒泡排序?从更简单的事情开始。跑之前先走。

看看内部循环,你有:

  push ebx
  push ecx
  push edx
  add esp,12

  jle .task

您将这 3 个寄存器推入堆栈并立即删除它们(您甚至没有将它们弹回各自的寄存器,因此不仅堆栈不平衡,而且寄存器包含错误的值)。既然你用 s “清理了堆栈” add esp, 12,只要你有你pop的 s,堆栈就是错误的。

于 2013-02-16T18:46:52.943 回答