The code below is an assembly code to read and write a single floating point number using scanf and printf.
extern scanf
extern printf
section .data
x dq 0.0
fmts db "%lf", 0
fmtp db "%lf", 0xA, 0
section .bss
section .text
global main
main:
push rbp
;push rax
;push rax
mov rdi, fmts ;scanf format
mov rsi, x ;The address of the variable
call scanf
mov rdi, fmtp ;printf format
movq xmm0, qword[x] ;The value of the variable
mov rax, 1
call printf
Exit:
pop rbp
mov rax, 1
mov rbx, 0
int 0x80
(To compile and run this code, it's easiest to use gcc
:
nasm -f elf64 ./a.asm && gcc -o ./a a.o -no-pie && ./a
)
This code works fine; but when we uncomment one of the push rax
lines, segmentation fault occurs. However, if we uncomment both of the push rax
lines, it will work fine again. It seems we either shouldn't push anything on the stack, or at least 128bit. It's worth mentioning that the values of the variables pushed onto the stack (in this case, rax
,) will be unchanged.
Can someone explain this behavior? Thanks in advance.