Buffers Are Not Flushed if the Program Crashes

C++ Primer 4/e在Managing the Output Buffer這個地方有一個警告:『Output buffers are not flushed if the program terminates abnormally. When attempting to debug a program that has crashed, we often use the last output to help isolate the region of program in which the bug might occur. If the crash is after a particular print statement, then we know that the crash happened after that point in the program.

When debugging a program, it is essential to make sure that any output you think should have been written was actually flushed. Because the system does not automatically flush the buffers when the program crashes, it is likely that there is output that the program wrote but that has not shown up on the standard output. It is still sitting in an output buffer waiting to be printed.

If you use the last output to help locate the bug, you need to be certain that all the output really did get printed. Making sure that all output operations include an explicit flush or call to endl is the best way to ensure that you are seeing all the output that the program actually processed.

Countless hours of programmer time have been wasted tracking through code that appeared not to have executed when in fact the buffer simply had not been flushed. For this reason, we tend to use endl rather than \n when writing output. Using endl means we do not have to wonder whether output is pending when a program crashes.』

中文版的這樣寫:『如果程式未能正常終止,output緩衝區並不會被清空。欲對非正常終止的程式偵錯,我們經常以「最後一個輸出」協助隔離可能的臭蟲發生區域。一旦在某特定列印述句後當掉,我們就知道問題是由該點之後的程式碼引起。

對程式偵錯時,很重要的一件事是「確認應該寫出的任何訊息都已被掃出緩衝區」。這是因為程式當掉時系統並不自動清空緩衝區,因此也許程式寫出了訊息但未顯示於標準輸出裝置上-它仍置於output緩衝區等待被印出。

如果你以上述的「最後一個輸出」協助定出臭蟲位置,必須確認所有輸出訊息真的都要被印出了。最好的辦法就是確保每一個輸出操作都包含一個明確的flush或endl。

程式員的工作生命中有無數小時浪費在追蹤似乎並沒有被執行起來的程式碼,而其實那也許只是緩充區沒被清空而已。因為這個原因,我們在輸出訊息時傾向使用endl而非’\n’,這可使我們在程式當掉時不需考慮output緩衝區到底有沒有被清空。』

緩衝區的flush及endl還滿玄的,好像我沒什麼印象出錯過,好吧記起來以備已後用到。

Print Friendly, PDF & Email

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料