.file "readlines.s"
# Assembler directives to allocate storage for static array
.section .rodata
fscanf_format_str:
.string "%d%d"
.globl readlines
.type readlines, @function
.text
readlines:
push %rbp # save caller's %rbp
movq %rsp, %rbp # copy %rsp to %rbp so our stack frame is ready to use
# store parameters on stack
subq $-24, %rsp
movq %rdi, -8(%rbp)
movq %rsi, -16(%rbp)
movl %edx, -20(%rbp)
# using fscanf tp read entire while
# set index
movl $0, -24(%rbp)
loop_body:
# if the number of real lines read by function is larger than expected, then break
movl -20(%rbp), %eax
cmpl %eax, -24(%rbp)
jge exit
# using fscanf to read line by line
movq -8(%rbp), %rdi
movq $fscanf_format_str, %rsi
# get the target address
movq -16(%rbp), %rdx
movslq -24(%rbp), %rax
imulq $16, %rax
leaq 12(%rdx, %rax), %rdx
movq -16(%rbp), %rcx
leaq (%rcx, %rax), %rcx
movq $0, %rax
call fscanf
# if fscanf return 0, then no line exists
cmpl $0, %eax
je exit
# do arithmetic on the two values read from file
movq -16(%rbp), %rdx
movslq -24(%rbp), %rax
imulq $16, %rax
movslq (%rdx, %rax), %r8
movslq 12(%rdx, %rax), %r9
addq %r8, %r9
movq %r9, 4(%rdx, %rax)
incq -24(%rbp)
jmp loop_body
exit:
leave
ret
.size readlines, .-readlines
The above code is a simple function called readlines, which serves for reading two integers line by line from an input file, but fscanf shows SIGSEGV fault in gdb, see below picture for details: