I am new to nasm and I really want to learn how to store a number with user input. I can't get rid of getting segmentation fault when using scanf. I have searched the web, but havent found any solution to this problem.
I tried this code but it doesn't work for me.
Can someone explain me what am I doing wrong?
global main
extern printf, scanf
section .data
msg: db "Enter a number: ",10,0
format:db "%d",0
section .bss
number resb 4
section .text
main:
mov rdi, msg
mov al, 0
call printf
push number
push format
call scanf
ret
Thanks in advance!
The x86-64 calling convention doesn't push the arguments generally. Additionally you have to tell a function with variable count of arguments, how many floating point arguments you provide.
This works:
global main
extern printf, scanf
section .data
msg: db "Enter a number: ",10,0
format:db "%d",0
section .bss
number resb 4
section .text
main:
sub rsp, 8 ; align the stack to a 16B boundary before function calls
mov rdi, msg
mov al, 0
call printf
mov rsi, number
mov rdi, format
mov al, 0
call scanf
add rsp, 8 ; restore the stack
ret
BTW: If you want to work with floating point numbers, you have to align the stack to a 16 byte boundary before calling the function.