-1

I am quite new to Assembly and I am trying to create a program that uses scanf to receive a number from the user. It then outputs "Result: (the number)" I keep getting a segmentation error upon running the code. This is the code I have got now:

.global main
mystring: .asciz"input\n"
formatstring: .asciz" %d"
resultstring: .asciz "Result: %ld\n"

main:
    movq    $0, %rax    
    movq    $mystring, %rdi
    call    printf
    call    inout
    movq    $0, %rax
    movq    $resultstring, %rdi
    call    printf
    jmp end

inout:
    pushq   %rbp
    subq    $8, %rsp
    leaq    -8(%rbp), %rsi
    movq    $formatstring, %rdi
    movq    $0, %rax
    call    scanf
    popq    %rbp    
    ret


end:
    movq    $0, %rdi
    call    exit

I suspect there is something wrong with the 'inout' method. Any solutions to make this program working?

  • 1
    in `inout` you don't set the `rbp`, only push the old value on stack, but then you access `rbp-8` memory (access happens inside scanf), which may point anywhere. BTW "I keep getting a segmentation error" shows lack of effort on your side, by debugging you should be able to tell at which instruction it segfaults, and what's the state of CPU (register values, address of code, stack content) ... but at that point you wouldn't need to ask at SO, as you would probably see by yourself the `%rsi` argument for `scanf` is bogus. – Ped7g Sep 29 '16 at 10:39
  • And you don't restore `rsp` after scanf call, doing `pop %rbp` with wrong `rsp` value. Also you should make sure the `rsp` is aligned upon call of `scanf`. Check this: http://cs.lmu.edu/~ray/notes/gasexamples/ (looks short enough and maybe complete, by 4 seconds quick look) – Ped7g Sep 29 '16 at 10:45
  • Some of the comments on what appear to be a similar question can be found here: http://stackoverflow.com/questions/39679848/simple-input-to-output-program-in-assembly – Michael Petch Sep 29 '16 at 14:09
  • One push and one `sub rsp, 8` misaligns the stack, too. The ABI requires it to be 16B-aligned before running CALL (which pushes an 8B return address). – Peter Cordes Sep 30 '16 at 15:26

1 Answers1

1
leaq    -8(%rbp), %rsi

In this instruction you are referring to the %rbp register but you forgot to actually initialize it!

Fifoernik
  • 9,779
  • 1
  • 21
  • 27