Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...