0

I'm trying to make an assignment that has to have the program ask for an integer, only to increment it by one, and then outputting it again. However, i'm getting the "Segmentation fault" error message after inputting said integer. I'm completely lost, please help, it's probably a very stupid mistake.

.global main

readString: .asciz "%ld"

main:
    subq $8, %rsp           # reserving space for the variable on the stack
    leaq -8(%rbp), %rsi     # loading the effective memory adress into %rsi
    movq $readString, %rdi  # Load the first argument of scanf into %rdi
    movq $0, %rax           # Clear %rax
    call scanf              # Calling scanf from the C library
    movq %rsi, %r9          # Loading the scanned integer into %r9
    inc  %r9                # Increment %r9 by one

    movq $0, %rax           # Clear %rax
    movq %r9, %rdi          # Loading the incremented integer into %rdi
    call printf             # Calling printf from the C library
    call end                # Ending the program

end:
    mov $0, %rdi            # Loading the exit code
    call exit               # Calling the exit code
TheNickqq
  • 63
  • 6
  • Use gdb to find out where you segfault. – Peter Cordes Sep 24 '17 at 16:51
  • 3
    Oh, you use `leaq -8(%rbp), %rsi`, but `%rbp` still has the caller's value. I think you want `mov %rsp, %rsi`, because `%rsp` is pointing to the memory you just reserved. `gdb` would have shown you this if you'd used it to single-step your code and watch register values. See the bottom of https://stackoverflow.com/tags/x86/info. – Peter Cordes Sep 24 '17 at 16:52
  • The other option is to set `%rbp` up as a "frame pointer" on entry to your function. You have other bugs, but you'll get to them with a debugger. (or see https://stackoverflow.com/questions/46389957/my-att-assembly-x86-x64-code-should-increment-but-doesnt for someone doing the same assignment, I think). I'm sure this question is a duplicate of one that's been asked before, but I haven't had any luck finding an existing one. :/ – Peter Cordes Sep 24 '17 at 16:58

0 Answers0