0

So I have this simple code:

.data
    n: .long 5
    s: .space 4
    format: .asciz "%d"
.text

.global main

main:
    mov $0, %eax

etloop:
    cmp n, %eax
    je etexit

    movl n, %ebx
    pushl %ebx
    push $format
    call printf
    pop %ebx
    pop %ebx

    push $0
    call fflush
    pop %ebx

    add %eax, s
    add $1, %eax
    jmp etloop

etexit:
    mov $1, %eax
    mov $0, %ebx
    int $0x80

It is supposed to print the sum of the numbers from 0 to 4. However, it looks like printing inside the loop creates an infinite one, even though the ecx register isn't affected.

Popescu Ion
  • 142
  • 10
  • 2
    `ecx` is a caller-saved register according to convention. `printf` is allowed to modify it. You should `push`-`pop` it. PS: do not use the exit system call if you use the C library. Return from `main` or `jmp exit`. Although your `fflush` does take care of the usual problem, it's still not recommended. – Jester Dec 03 '20 at 15:55
  • So how can I print the numbers in the loop? Let's say I have n of them and with a more compex format – Popescu Ion Dec 03 '20 at 15:58
  • 1
    Yes, or choose a different register which is callee-saved, such as `%edi` or `%esi`. This will mean you have to write a manual compare and conditional jump instead of using the `loop` instruction, but `loop` is generally not recommended in modern code anyway. – Nate Eldredge Dec 03 '20 at 15:58
  • Why call `fflush` on `stdin`? – Erik Eidt Dec 03 '20 at 15:59
  • @ErikEidt: That's `fflush(NULL)` which flushes everything, including stdout which is normally line-buffered. stdio functions take pointers, not fds. It is still kinda pointless, though; either way the output basically appears instantaneously, whether it's with 1 or multiple `write` system calls. – Peter Cordes Dec 03 '20 at 16:00
  • @NateEldredge Ok, so I edited the code to a version without loop. But the result is the same. Also, I see no difference between using %eax and %ecx for looping, the problem is still there. – Popescu Ion Dec 03 '20 at 16:03
  • `eax` is also caller-saved. Heck, that's the return value from `printf`. – Jester Dec 03 '20 at 16:07
  • @Jester So what is the solution after all? – Popescu Ion Dec 03 '20 at 16:08
  • 1
    As we have said, either `push` and `pop` or use `esi` or `edi` which are callee-saved. – Jester Dec 03 '20 at 16:09
  • Yeah, it worked. Thanks! – Popescu Ion Dec 03 '20 at 16:11

0 Answers0