I'm learning programming in Assembly x86 using the GNU Assembler "as". I'm trying to write a simple program which first asks user for input (a one-digit number), increments that number, then prints it out.
This is what I tried:
# AT&T Syntax used.
inout: # subroutine: inout
movq $0, %rsi
movq $request, %rdi
call printf # Prints: "Enter a number please"
movq %rsp, %rbp
subq $8, %rsp
leaq -8(%rbp), %rsi
movq $formatstr, %rdi
movq $0, %rax
call scanf # Scan for input
movq -8(%rbp), %rax # copy the number from the stack to a register
incq %rax # increment it
movq %rbp, %rsp
popq %rbp # reset the stack
movq $0, %rsi
movq %rax, %rbx
movq $result, %rcx
call printf # print the string: "The result is: %d\n"
ret
.text # variables
string: .asciz "inout\n"
request: .asciz "Enter a number please\n"
formatstr: .asciz "%1d"
result: .asciz "The result is: %d\n"
.global main # Subrountine : main
main:
movq $0, %rax
movq $string, %rdi
call printf # print string "inout"
call inout
end: # end of program
mov $0, %rdi
call exit
Then I compile and run using the following two commands:
gcc -o inout.o inout.s -no-pie
./inout.o
I get the first two lines printed, I enter a number (1), then I get segmentation fault:
"inout
Enter a numbers please"
1
Segmentation fault
Could you please check what I am doing wrong? Thanks in advance.