-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

u plsは私の間違いを見つけるのに役立ちますか?よろしくお願いします

4

1 に答える 1

0

なぜバブルソートをしようとしているのですか?もっと簡単なことから始めましょう。走る前に歩く。

内側のループを見てください。

  push ebx
  push ecx
  push edx
  add esp,12

  jle .task

これらの 3 つのレジスタをスタックにプッシュし、すぐに削除します (それらをそれぞれのレジスタに戻すことさえしなかったため、スタックのバランスが取れていないだけでなく、レジスタに間違った値が含まれています)。で「スタックをクリーンアップ」したadd esp, 12ので、 があるときはいつでもpopスタックが間違っています。

于 2013-02-16T18:46:52.943 に答える