使用nasm中的scanf进行数组输入

时间:2018-03-20 14:36:09

标签: assembly nasm x86-64

我尝试使用循环读取数组的浮点输入,然后打印数组。 读取n值后,会出现分段错误。我无法弄清楚出了什么问题。我该如何纠正错误?

%macro exit 0
    mov rax,60
    mov rdi,0
    syscall
%endmacro
extern printf 
extern scanf
;-------------------------------------------
section .data
    nfmt db "%d",0
    nfmtout db "%d",10,0
    formatsf db "%lf",0
    formatpf db "%lf",10,0
;-------------------------------------------
section .bss
    n resq 1
    array resq 10
;-------------------------------------------
section .code
global main
main:

    push rbp            ;creating stack frame
    mov rbp, rsp

;read no of elements in array n 
    mov rdi,nfmt
    mov rsi,n
    mov rax,0           ;no of floating pt params
    call scanf


; read elements
    mov rcx,[n]
    mov r8,0
    mov rbx,array
back:   
    push rcx                
    mov rdi,formatsf
    lea rsi, [rbx+r8*8]     
    mov rax,0
    call scanf
    add r8,1
    pop rcx 
    loop back


    xor rax,rax

;print the array    
    mov rcx,[n]
    mov r8,0
    mov rbx,array
back2:
    push rcx    
    mov rdi,formatpf
    movq xmm0, [rbx+r8*8]
    mov rax,1
    call printf
    add r8,1
    pop rcx
    loop back2              


    mov rsp,rbp         ;destroying stack frame
    pop rbp
    exit

节目输出

5
12.0
12.2
158.9
156.3
256.7
Segmentation fault (core dumped)

当我将格式说明符更改为读取整数值时,输出很奇怪。

; read elements
    mov rcx,[n]
    mov r8,0
    mov rbx,array
back:   
    push rcx                
    mov rdi,nfmt       ;format specifier changed
    lea rsi, [rbx+r8*8]     
    mov rax,0
    call scanf
    add r8,1
    pop rcx 
    loop back


    xor rax,rax

;print the array    
    mov rcx,[n]
    mov r8,0
    mov rbx,array
back2:
    push rcx    
    mov rdi,nfmtout      ;format specifier changed
    mov rsi, [rbx+r8*8]  ;xmm0 register replaced by rsi
    mov rax,0
    call printf
    add r8,1
    pop rcx
    loop back2      

进行上述更改后的输出

5
12
45
845
965
123
12
123
123
123
123

0 个答案:

没有答案