NASM x86_64 scanf segmentation fault

前端 未结 1 1157
离开以前
离开以前 2020-12-21 15:51

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,

1条回答
  •  自闭症患者
    2020-12-21 16:05

    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.

    0 讨论(0)
提交回复
热议问题