1

I am attempting to use the _printf function, and everything works OK except for one thing: it prints the result twice. The issue is that I am not receiving any errors other than the unexpected behavior. I attempted to add a null terminated character but was unable to change the result. However, that should not be an issue since if I am not incorrect, the string should be defaulted to make the string null terminated.

I am compiling the code with:

as --32 ./bin/assembly.asm -o ./bin/a.o
ld -m i386pe ./bin/a.o -o ./bin/a -lmsvcrt

The assembly code:

.section .text
    .global _start
_start:
    call main
    movl %eax, %ebx
    movl $1, %eax
.section .data
LC0:
    .string "hello\0"
.section .text
main:
    pushl %ebp
    movl %esp, %ebp
    sub $0, %esp
    pushl $LC0
    call _printf
    add $4, %esp
    movl $0, %eax
    leave
    ret

The output:

hellohello

I have tried to reinstall the msvcrt.dll but that did not help, have also tried to restart the computer, have also tried to use puts and putchar but with the same result.

ilittlebig
  • 21
  • 3
  • What do you think happens after the final instruction of `_start` is reached? – fuz Dec 22 '22 at 00:03
  • 1
    Since you are asking, I would assume that it keeps on reading the code, which results in main being run twice? However, I am unsure of it works like that. I tried adding a `leave` and `ret` but that resulted in a `segfault` – ilittlebig Dec 22 '22 at 00:05
  • Yes, your understanding is correct. Try calling the `_exit` function to end the process. – fuz Dec 22 '22 at 00:06
  • I feel stupid. Thank you, that worked. – ilittlebig Dec 22 '22 at 00:06
  • Single stepping with a debugger is a good way to catch "stupid" / obvious mistakes before telling other humans about them. :P Every has brain farts, debuggers reduce the amount of farting in public. In this case you'd see execution fall through into `main` again after it returned. Not exactly a duplicate of [What if there is no return statement in a CALLed block of code in assembly programs](https://stackoverflow.com/q/41205054) since `_start` isn't called by anything else. But I think close enough. – Peter Cordes Dec 22 '22 at 04:27
  • I'm surprised the CPU didn't try to read the `.data` section as code and crash. But then again, the assembler is probably smart enough to put `data` before `text` no matter where it is in your document. – puppydrum64 Dec 22 '22 at 13:20

0 Answers0