x86 Assembly - printf doesn't print without “\n”

好久不见. 提交于 2021-01-28 07:31:08

问题


So I'm confused. I'm going through the book "Programming from the Ground Up" and am working with using libraries.

printf is working just fine so long as I include a "\n" in the string, but without it it will print absolutely nothing.

Any idea why this happens?

Code:

.section .data

my_str:
        .ascii "Jimmy Joe is %d years old!\n\0"

my_num: 
        .long 76

.section .text

.globl _start
_start:
        pushl my_num
        pushl $my_str
        call printf

        movl $1, %eax
        movl $0, %ebx
        int $0x80

Also, when I use -m elf_i386 for 32-bit mode and -dynamic-linker /lib/ld-linux.so.2 -lc to link, I get the warning

ld: skipping incompatible /usr/lib64/libc.so when searching for -lc

If that makes any difference, or if anybody has any suggestions as to how to have it load the 32-bit library directly.

Thanks!


回答1:


The problem is that printf by default just prints stuff into the stdout buffer. Things won't actually be printed until the buffer is flushed. The depends on the buffering mode of stdout, but, by default, it is line-buffered, which means it gets flushed every time you print a newline character.

To flush explicitly in C, you call fflush; you can do that in asm code with

pushl stdout
call fflush
addl $4, %esp

Alternately, you can call the stdlib exit function (which flushes all I/O buffers before actually exiting), instead of using the _exit system call, which does not.




回答2:


It seems you try to link your 32-bit program against the (system default) 64Bit c library. Check if you have libs32 packages installed. To find out which libraries a program or other dynamically loads froum the LD_LIBRARY_PATH use ldd <name_of_your_binary> As to why the newline is required I can only speculate that it flushes the output buffer. See also Why does printf not flush after the call unless a newline is in the format string?



来源:https://stackoverflow.com/questions/24093313/x86-assembly-printf-doesnt-print-without-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!