2012-03-24 33 views
0

我有一个真的简单的程序,但它不起作用。此外,这让我对程序的流程产生了严重的怀疑。无法解释的错误(Segm.fault 11)与gcc4.2.1

的程序是这样的(假设必要的标头):

main(){ 
printf("hello1"); 
printf("hello2"); 
somefunction(); 
} 

输出是在至少奇特:它给我回来只是第一个printf(hello1),随即该程序,错误退出“分割故障11“。 但是,如果我删除'somefunction()'第二个printf是ALSO显示。

我的意思是,如果我的'somefunction()'有问题,第二个printf()应该不管显示。

+1

编译所有警告。 – 2012-03-24 13:06:42

回答

5

您的somefunction做了一件令人讨厌的事情,在printf有机会刷新缓冲区之前,进程被杀死。您可以尝试:

printf("hello1"); 
printf("hello2"); 
fflush(stdout); 
somefunction(); 
+0

谢谢,我不知道这一点。现在我可以尝试调试某些功能。 – ClausW 2012-03-24 13:12:45

2

stdout是行缓冲的。这意味着你的输出被缓冲到稍后要打印的地方,但是由于你的somefunction崩溃,它没有机会打印它们。

您可以刷新使用fflush缓冲区:

fflush(stdout); 

或者,打印新行:

main(){ 
    printf("hello1\n"); 
    printf("hello2\n"); 
    somefunction(); 
} 
0

在一般情况下,你应该始终把\n在打印语句的结束,除非你确切地知道你在做什么。这将确保语句实际上将其输出。

printf("hello1\n"); 
printf("hello2\n"); 
somefunction();