man7.org中声明为无效的有效程序 [英] a valid program being declared as invalid by man7.org

查看:137
本文介绍了man7.org中声明为无效的有效程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关使用缓冲区的功能的手册,请参阅 http:/ /man7.org/linux/man-pages/man3/setbuf.3.html ,下面的一段代码被声明为无效。但是,当我在我的机器上尝试时,事情进展顺利:

  #include< stdio.h> 

int
main(void)
{
char buf [BUFSIZ];
setbuf(stdin,buf);
printf(Hello,world!\\\
);
return 0;
}

这个年龄的原因是:


您必须确保 buf 指向的空间仍然存在
时间流已关闭,这也发生在程序


我在该段代码中看不到任何错误。它也很顺利。是不是对?任何人可以向我解释吗?



############################## ##############################################################################################################。但 stdin 存活。



但是,有一个默认缓冲区留给 stdin
并且,我们可以假设 stdin 是一个流,并且有一些方法来销毁或关闭该流?

解决方案

错误消息已经解释得很清楚。在您的代码片段中, main 返回时, buf 被销毁,但 stdin 跨越 main 。在已返回但在 stdin 已关闭之前的时间段内,您将有一个打开的 stdin 使用无效的缓冲区。这可能会导致问题。例如,如果有一个全局类对象的析构函数使用 stdin 进行输入,你认为会发生什么?



您还可以查看此问题


In the manual about functions of buffer-using given at http://man7.org/linux/man-pages/man3/setbuf.3.html, a piece of code below is declared as invalid. However, when I try that on my machine, things go well:

 #include <stdio.h>

   int
   main(void)
   {
       char buf[BUFSIZ];
       setbuf(stdin, buf);
       printf("Hello, world!\n");
       return 0;
   }

The reason given by that age is :

You must make sure that the space that buf points to still exists by the time stream is closed, which also happens at program termination.

I can't see any mistake in that piece of code. And it also goes well too. Is it right or not? Can any one explain it to me?

################################################2

as @Lingxi have answered below, the buffer will be destroyed after the main function return. But stdin survive.

But, is there a default buffer left for the stdin ? And also, can we assume that the stdin is a stream, and there is some ways to destroyed or close that stream?

解决方案

The error message has explained it quite clearly. In your code snippet, buf is destroyed when main returns, but the lifetime of stdin spans beyond main. During the time period after main has returned but before stdin is closed, you would have an opened stdin with an invalid buffer. This may cause problems sometimes. As an example, what do you think would happen if there is a global class object whose destructor uses stdin for input?

You may also want to have a look at this question.

这篇关于man7.org中声明为无效的有效程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆