汇编语言x86中的字符串反向

时间:2016-10-26 18:35:09

标签: string assembly x86 reverse irvine32

我是汇编语言的新手,我有这个代码,假设要反转字符串长度,现在我知道我已经关闭,但程序因为某种原因不断崩溃。问题在于STRREV PROC。我在这段代码中做错了什么?

INCLUDE Irvine32.inc
.data
    prompt BYTE "Enter String: ", 0
    response BYTE 50 DUP(0)
    message BYTE " Message entered. ",0
.code   

swap MACRO a,b 

    xor a,b
    xor b,a
    xor a,b

endM

STRQRY PROC
   push ebp
   mov  ebp, esp
   push edx
   push ecx

   mov edx, [ebp+8]
   call writestring

   mov ecx, SIZEOF response
   mov edx, OFFSET response
   call readstring


   pop ecx
   pop edx
   pop ebp  
   ret 4

STRQRY ENDP

STRLEN PROC 
           push ebp 
           mov  ebp, esp
           push ebx
           push ecx

           mov edx,[ebp+16]

           mov eax, 0


counter:
           mov cl,[edx+eax]

           cmp cl, 0       

           JE  done

           inc eax 

           jmp counter

done:
           pop ecx
           pop ebx
           pop ebp
           ret 4

STRLEN ENDP

STRREV proc
    push ebp
    mov  ebp, esp

    push OFFSET response   
    call STRLEN

    mov edx, [ebp+8]
    mov esi, 0
    dec eax

reverseloop:   

    mov ah, [edx+esi]
    mov al, [edx+eax]

    swap ah, al

    mov [edx+esi],ah
    mov [edx+eax],al

    inc esi
    dec eax

    cmp esi, eax
    jb reverseloop
    ja finish

finish:
    pop ebp
    ret 4

STRREV endp

main PROC

    push OFFSET prompt
    call STRQRY

    call writedec 

    mov edx,OFFSET message
    call WriteString

    push eax 
    call STRREV

    mov edx, OFFSET response
    call WriteString

     exit
main ENDP
END main

1 个答案:

答案 0 :(得分:1)

在你的函数的主要问题是改变AL和AH寄存器,然后用EAX的指针。
我决定根据你的代码写一个新的功能,使用正确的模拟器仔细阅读和调试代码。

STRREV proc 

;opening the function 
push ebp
mov  ebp, esp

push OFFSET response  
call STRLEN

mov edx, [ebp+8]   ;edx = offset string to reverse 
mov esi, 0
dec eax    

mov ebx,edx       ;ebx stores the pointer to the first character  
add ebx,eax`       ;now ebx store the pointer to the last character before the '$'  

reverseloop:   


mov ah, [edx]    ;ah stores the value at string[loop count]
mov al, [ebx]    ;al stores the value at string[len-loop count-1]

;"swap ah,al"  is logiclly unnecessary
;better solution: 

mov [ebx],ah     ; string[loop count] = string[len-loop count-1]
mov [edx],al     ; string[len-loop count-1] = string[loop count]

inc edx          ;increment  of the right-most pointer
dec ebx          ;decrement of the right-most pointer 

cmp ebx, eax     ;compares the left-most pointer to the right-most 
jb reverseloop
jmp finish      ;"ja", there is no need to check a condition twice 

finish:
pop ebp
ret 4

STRREV endp