13

If fclose(0) is called, does this close stdin?

The reason why I'm asking this is that for some reason, stdin is being closed in my application and I cannot figure out why. I checked for fclose (stdin) and this is not in the application and so I was wondering if fclose(0) could cause undefined behaviour such as closing stdin?

If not, what are other ways that stdin could be erroneously closed?

bbazso
  • 1,959
  • 6
  • 22
  • 30
  • fileno( stdin ) == 0, but stdin != 0 – William Pursell May 10 '11 at 14:36
  • 1
    You are asking for *wrong* ways to close stdin ? Then I guess most of us are doing it right now :-? – cnicutar May 10 '11 at 14:38
  • Are you sure it is being closed *in* your app and not *before* your app? Does `stdin` work correctly at the beginning of one run of your program, and then stop working in the middle of the run? If not, perhaps the program that invoked yours closed (or never set up) stdin. – Robᵩ May 10 '11 at 17:36
  • Possible duplicate of [fclose() causing segmentation fault](http://stackoverflow.com/questions/1443164/fclose-causing-segmentation-fault) – Jim Fell Nov 13 '15 at 22:21

4 Answers4

22

The signature of fclose is this:

int fclose ( FILE * stream );

That means, fclose expects a pointer to FILE object. So if you pass 0, instead of a pointer, 0 would be understood as NULL pointer1. If its NULL pointer, how do you expect it to close stdin? It will not close. Use fclose(stdin), as stdin itself is a pointer to FILE object.

I think you're confusing stdin with file-descriptor which is of integral type, and usually denoted as fd. Its true that fd of input stream is 0. So if you want to use fd (instead of FILE*), then you've to use close from <unistd.h>.

#include <unistd.h>
int close(int fildes);

That is, close(0) would close stdin.

1 : It seems interesting that if you had passed 1 to fclose with the intention to close stdout, your code wouldn't even compile, and you would immediately see the problem with your code at compile-time itself. Now the question is, why would it not compile? Because unlike 0, 1 is not implicitly converted into pointer type. The compiler would generate message like "error: invalid conversion from ‘int’ to ‘FILE*’. See the error and line number here at ideone.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
7

fclose(0) invokes undefined behavior, so yes, it could do anything, including closing stdin. But you have much bigger problems if fclose(0) appears in your code.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
6

I think it will take it as fclose(NULL); Which should be undefined and may crash.

Mayank
  • 5,454
  • 9
  • 37
  • 60
  • 3
    It's sometimes defined AS a crash :) From the Mac OS X man page: The fclose() function does not handle NULL arguments; they will result in a segmentation violation – Matt K May 10 '11 at 14:43
6

The following closes stdin: close(0); fclose(stdin); close(STDIN_FILENO); daemon(0, 0);

Mel
  • 6,077
  • 1
  • 15
  • 12