首页 > 解决方案 > 在此程序集 x86 代码 (NASM) 中获取 Seg-fault

问题描述

我正在编写一个简单的代码,该代码接收指向仅包含数字的以空字符结尾的字符串的指针并将其转换为十六进制。像“479”-> 1DF,但我在pop eax中遇到分段错误!请问有什么帮助吗? 注意:组装 x86

gdb 上的错误:无法访问内存 ar 0xfff...


lop:
    push  dword[edi]
    inc byte [co]
    mov edi, an
    jmp loop

fin:
    push dword[edi]
    inc byte [co]
    jmp finish

loop:
    mov edx, [co]
    cmp edx, 0
    je done
    dec edx
    pop eax
    mov [edi], eax
    inc edi
    jmp loop 


完整代码:

section .data
    co: dd 0
    hex: dd "123456789ABCDEF"   

section .rodata                     ; we define (global) read-only variables in .rodata section
    format_string: db "%s", 10, 0   ; format string

section .bss                        ; we define (global) uninitialized variables in .bss section
    an: resb 12                     ; enough to store integer in [-2,147,483,648 (-2^31) : 2,147,483,647 (2^31-1)]

section .text
    global convertor
    extern printf

convertor:
    push ebp
    mov ebp, esp    
    pushad          

    mov ecx, dword [ebp+8]      ; get function argument (pointer to string)
    mov edx, ecx                    ; our string

    mov ebx, 16
    xor eax, eax                    ; zero a "result so far"
top:
    movzx ecx, byte [edx]           ; get a character
    inc edx                         ; ready for next one
    cmp ecx, '0'                    ; valid?
    jb finish
    sub ecx, '0'                    ; "convert" character to number
    imul eax, 10                    ; multiply "result so far" by ten
    add eax, ecx                    ; add in current digit
    jmp top                         ; until done


finish:
    mov edi, hex
    xor edx, edx
    cmp eax, ebx
    jl hello
    div ebx
innerLoop:
    cmp edx, 1
    je fin
    inc edi
    dec edx
    jmp innerLoop

hello:
    cmp eax, 1
    je lop
    inc edi
    dec edx
    jmp hello

lop:
    push  dword[edi]
    inc byte [co]
    mov edi, an
    jmp loop

fin:
    push dword[edi]
    inc byte [co]
    jmp finish

loop:
    mov edx, [co]
    cmp edx, 0
    je done
    dec edx
    pop eax
    mov [edi], eax
    inc edi
    jmp loop 

done:               
    push an                     ; call printf with 2 arguments -
    push format_string          ; pointer to str and pointer to format string
    call printf
    add esp, 8                      ; clean up stack after call

    popad           
    mov esp, ebp    
    pop ebp
    ret

标签: assemblyx86segmentation-fault

解决方案


推荐阅读