Output not printing without fflush(stdout)

*爱你&永不变心* 提交于 2019-12-05 10:12:31

I don't understand why sometimes I need to use fflush() and sometimes not.

Sometimes the stdio buffers are flushed sometimes they aren't. For example simply including a "\n" in the printed stuff will typically flush it (because stdout is by default line-buffered when attached to a terminal).

When a program segfaults, does stdout not flush its buffer automatically ?

Stdio buffers are flushed by exit. When a signal (such as SIGSEGV) kills a process, exit is not called. Another way to exit a process without flushing the stdio buffers is to use the Unix-specific call _exit.

No, why should it. The program gets killed by the operating system. If a segfault occurs, the program is no longer in a meaningful state, so nothing can safely happen at that point other than immediate termination.

(And don't nobody try to register a signal handler for SIGSEGV.)

"I cannot figure out why fflush (stdout) is called here in this code I try to comment this line and behavior was exactly the same."

Because you're not guaranteed to see previous printf() output if that output doesn't end in a newline.

Basically, you only need it if you're displaying say a prompt without a newline, and you want to make sure the user can see it.

See this site.

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