G ++编译器:Segfault处理 [英] G++ compiler: Segfault handling
问题描述
我正在一个项目,我调用一个函数触发一个segfault。我修复了这个问题,但在此过程中,我注意到了以下问题。
当我的代码是格式时:
< p $ p>
main(){
...
std :: cout< 寻找segfault\\\
; //这不打印
buggyFunction(); // crashes in here
...
}
buggyFunction(){
...
thing_that_causes_segfault;
...
}
Looking for segfault t打印到STD,程序崩溃在buggyFunction。好,但是当我在buggyFunction()中添加cout线时;
main(){
...
std :: cout<< 寻找segfault\\\
; // this now * does * print
buggyFunction();
...
}
buggyFunction(){
...
std :: cout< 现在我们是INSIDE buggy function\\\
; // this prints too
thing_that_causes_segfault;
...
}
那么它崩溃)。
为什么我们看到ouput的这个区别,这取决于这个额外的输出调用的添加?它与流的处理有关还是别的什么?我使用的是g ++(Ubuntu 4.4.3-4ubuntu5)4.4.3。
c $ c> cout 有一个缓冲区,它只会传递到系统函数,并在缓冲区已满时写入控制台。您的第二次使用 cout
恰好溢出缓冲区,因此调用操作系统并清空缓冲区。如果你想保证输出已经离开缓冲区,你必须使用 std :: flush
。你可以结束一行,并用 std :: endl
冲洗缓冲区。
I'm working on a project where I call a function which triggers a segfault. I fixed this, but during the process I noticed the following.
When my code is of the format;
main(){
...
std::cout << "Looking for segfault\n"; // this does not print
buggyFunction(); // crashes in here
...
}
buggyFunction(){
...
thing_that_causes_segfault;
...
}
The line "Looking for segfault" doesn't print to STD, and the program crashes in buggyFunction. Fine, but when I add a cout line inside buggyFunction();
main(){
...
std::cout << "Looking for segfault\n"; // this now *does* print
buggyFunction();
...
}
buggyFunction(){
...
std::cout << "Now we're INSIDE buggy function\n"; // this prints too
thing_that_causes_segfault;
...
}
Inside buggy function, both lines print (and then it crashes).
Why do we see this difference in ouput, depending on the addition of this extra output call? Is it related to the handling of streams, or something else? I'm using g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3.
The reason for this is that cout
has a buffer and it will only pass to the system function and write to the console when the buffer is full. Your second use of cout
happens to overflow the buffer and so it calls the operating system and empties the buffer. If you want to guarantee that the output has left the buffer, you must use std::flush
. You can both end a line and flush the buffer with std::endl
.
这篇关于G ++编译器:Segfault处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!