1

Here is my program:

section .text

extern printf, scanf

global main

main:
    mov rdi, msg1
    mov rax, 0
    call printf

    mov rsi, res
    mov rdi, fmt
    mov rax, 0
    call scanf

    mov rsi, [res]
    mov rdi, msg2
    mov rax, 0
    call printf

    ret

section .data
    fmt db '%d', 0
    msg1 db 'Please give a number: ', 0
    msg2 db 'Your number is %d', 10, 0
    res dq 0

From gdb, I got :

"Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7e4d88a in _IO_vfscanf () from /lib/x86_64-linux-gnu/libc.so.6"

What did I do wrong?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Jonas Daverio
  • 251
  • 2
  • 3
  • 7
  • Does this answer your question? [How to use scanf in NASM?](https://stackoverflow.com/questions/10973650/how-to-use-scanf-in-nasm) – Renat Dec 24 '19 at 16:53
  • @Renat No, this x86 and not x86-64, and the calling convention isn't the same. The strange thing is here calling convention is resepcted... – Jonas Daverio Dec 24 '19 at 16:58
  • 1
    You need to align the stack. Subtract 8 from rsp before calling other functions. – prl Dec 24 '19 at 17:51
  • @prl I don't see why that would be the cause. The printf parts work if I comment out the scanf call. EDIT: well, it works, but I don't understand why I have to do it there and not before printf... – Jonas Daverio Dec 24 '19 at 18:04
  • 1
    Because undefined behavior means that sometimes it does what you thought it should. Printf does require the stack to be aligned, and will fail under some conditions if it isn’t. – prl Dec 24 '19 at 18:34

0 Answers0