Why does printf output not appear right away when stepping through the code?

点点圈 提交于 2019-12-18 09:26:48

问题


I'm using Anjuta and gdb on Fedora 20 and created a C Makefile project. The code looks like this:

#include <stdio.h>

int main (void)
{
°   printf ("1");
°   printf ("2");
°   printf ("3");

    return (0);
}

° means I set a breakpoint at that position.

Now when I debug the code, there's no output while the current line is one of these printf-functions. Only when I exit main '123' appears in the terminal.

If I add \n to the second printf argument, then '12' appears as output when I move from breakpoint 2 to the 3rd one.


回答1:


By default, stdout is line buffered when writing to a terminal, fully buffered when writing to any other type of stream. Since you're not printing any newlines, the output is being buffered. You can change the buffering mode with setbuf(), end each string with newline, or call fflush() when you want printing to take plac.




回答2:


This is because printf writes to stdout which happens to be buffered. For more details see here.




回答3:


Add fflush(stdout) after each printf. Your output is small and remains in buffer until the progam exits.



来源:https://stackoverflow.com/questions/19757937/why-does-printf-output-not-appear-right-away-when-stepping-through-the-code

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