I'm trying to read floating point input for array using loop and then printing the array. After reading n values, it gives segmentation fault. I can't figure out what is wrong. How can i correct the error?
%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
Output of the program
5
12.0
12.2
158.9
156.3
256.7
Segmentation fault (core dumped)
When I change the format specifiers to read integer values the output is strange.
; 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
Output after making above changes
5
12
45
845
965
123
12
123
123
123
123