Print integers by using printf GAS

53 Views Asked by At

In the program below, I am trying to print out even numbers from 2 to n, with n passed in as an argument for function void even(int n). I have a different main.c file to call this function.

.extern printf
.section .data
format:
    .asciz "%d\n"

.section .text
.global even
even:
    cmpl $2, %edi #compare n to 2
    jl less_than_two #if n < 2 then jump to less_than_two
#if not, start from 2
    movl $2, %ebx           # start from 2

loop:
    # print the number
    movl $format, %esi # the string format of printf is in esi
    movl %ebx, %edi # the first argument of printf is in edi
    subq $8, %rsp # make room on the stack for the argument
    movl %edi, (%rsp) # push the argument onto the stack
    call printf
    addq $8, %rsp # clean up the stack

    addl $2, %ebx #add 2 to ebx
    cmpl %ebx, %edi # compare n with ebx
    jl end # if n < ebx then jump to end
    jmp loop #else continue to print

less_than_two:
    movl $format, %esi
    xorl %edi, %edi
    subq $8, %rsp # make room on the stack for the argument
    movl %edi, (%rsp) # push the argument onto the stack
    call printf
    addq $8, %rsp # clean up the stack
    ret

end:
    ret

When I try to compile and run it on Linux terminal, I get the result as: Segmentation fault (Core dumped).

1

There are 1 best solutions below

1
Chris Dodd On

In x86_64 Linux, arguments are passed in registers, not on the stack, so your printing code should be more like

    # print the number
    leaq format(%rip), %rdi   # the string format of printf is in rdi
    movl %ebx, %esi           # the first int argument of printf is in esi
    xor %eax, %eax            # set %al to 0 for no args in xmm regs
    call printf

See the ABI spec for all the gory details