473,796 Members | 2,903 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

fclose(0)

This short program:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
int status;

status=fclose(0 );

printf("fclose( 0) status: %d\n",status);

}

crashes on the first two implementations I tried. Then I tried DMC and that
gave the expected EOF status.

Given the emphasis on error-checking in this group, it seems astonishing
that a library function (executed at most once per file) cannot do this
elementary check on it's parameter.

(It's possible a zero FILE* handle is returned by fopen() but the file has
to be closed for other reasons before it can checked by the application.)

Was I unlucky or is it normal for C library functions to be so fragile?

-- Bart
Jun 27 '08
53 4484
Richard Heathfield wrote:
Bartc said:

<snip>
>If this was the case then it would be better to admit it rather than
suggest, as a few people have, that crashing on passing a null pointer is
actually a good idea.

Crashing is not an idea - either good or bad. It is merely a consequence.

If a programmer is dense enough to break the contract between himself and
the implementation, he has no business complaining when something happens
that he doesn't like. If you don't want a crash or some other bad
consequence of passing an invalid argument (and neither do I), the answer
is simple: ***don't pass an invalid argument***.
I'm not sure it's invalid. Consider..

FILE *fp = fopen("file", "r");

which fails for some reason. Later in the program we do..

int stat = fclose(fp);

The fclose finds that fp does not point to an open file and returns EOF.

No crash, no problem.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Jun 27 '08 #21
Joe Wright said:
Richard Heathfield wrote:
<snip>
>If you don't want a crash or some other
bad consequence of passing an invalid argument (and neither do I), the
answer is simple: ***don't pass an invalid argument***.
I'm not sure it's invalid. Consider..

FILE *fp = fopen("file", "r");

which fails for some reason. Later in the program we do..

int stat = fclose(fp);
If fp is a null pointer, the argument *is* invalid, because fclose requires
fp to be a pointer to a stream that is associated with a file. A null
pointer doesn't qualify, since it is guaranteed not to point to any
object.
The fclose finds that fp does not point to an open file and returns EOF.
That is one legitimate outcome of undefined behaviour, yes. As you know,
there are plenty of others.
No crash, no problem.
I'm not sure I agree about the "no problem" part.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #22
Richard Heathfield wrote:
Joe Wright said:
>Richard Heathfield wrote:

<snip>
>>If you don't want a crash or some other
bad consequence of passing an invalid argument (and neither do I), the
answer is simple: ***don't pass an invalid argument***.
I'm not sure it's invalid. Consider..

FILE *fp = fopen("file", "r");

which fails for some reason. Later in the program we do..

int stat = fclose(fp);

If fp is a null pointer, the argument *is* invalid, because fclose requires
fp to be a pointer to a stream that is associated with a file. A null
pointer doesn't qualify, since it is guaranteed not to point to any
object.
It's a pity that case isn't specified in the way malloc/free is.

It is always safe to call free with the result of malloc, so it would be
consistent to always be a able to call any resource freeing function
with the result of its corresponding allocation function.

--
Ian Collins.
Jun 27 '08 #23
Bartc wrote:
"Eric Sosman" <es*****@ieee-dot-org.invalidwrot e in message
news:XI******** *************** *******@comcast .com...
>Bartc wrote:
>>"Richard Heathfield" <rj*@see.sig.in validwrote
The Standard requires that you pass to fclose a pointer to a stream
object
of type FILE. You did not do this. (0 doesn't point to any object at
all,
let alone a stream object.) You broke the rules, so all bets are off.
> The relevant passage is Section 7.1.4 paragraph 1:

"Each of the following statements applies unless
explicitly stated otherwise [...]: If an argument to
a function has an invalid value (such as [...] a null
pointer, [...]) [...]the behavior is undefined. [...]"

I suspect this was written when there were already many implementations that
behaved this way.
The Committee's mandate was not to invent a new programming
language from whole cloth, but to codify existing practice insofar
as practical.

In the Rationale, the Committee laid out the principles that
it tried to apply when making decisions about the language. One
of these was "Keep the spirit of C," and the very first point in
the short list of facets that constitute that spirit is "Trust
the programmer." As Richard Heathfield pointed out earlier, trust
is not a one-sided relationship; the trusted party bears a burden
arising from the fact of being trusted.
If this was the case then it would be better to admit it rather than
suggest, as a few people have, that crashing on passing a null pointer is
actually a good idea.
The good idea is not to pass a null pointer in the first place.
If you want a hand-holding language (and there's no shame in wanting
such a thing), you can find plenty of them.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jun 27 '08 #24
In article <i-*************** *************** @comcast.com>
Eric Sosman <es*****@ieee-dot-org.invalidwrot e:
In the Rationale, the Committee laid out the principles that
it tried to apply when making decisions about the language. One
of these was "Keep the spirit of C," and the very first point in
the short list of facets that constitute that spirit is "Trust
the programmer." As Richard Heathfield pointed out earlier, trust
is not a one-sided relationship; the trusted party bears a burden
arising from the fact of being trusted.
A burden and a benefit, simultaneously. :-)
The good idea is not to pass a null pointer in the first place.
And yet, if this is the case, why does free() accept NULL? The
same argument holds here, and -- historically speaking -- at the
time the C89 standard was being created, actual implementations
actually crashed if you called free(NULL). So the committee have
attempted to have it both ways: "We trust you (putting the burden
of checking for NULL first) when you call fclose(), but we do not
trust you (removing the burden of checking for NULL first) when
you call free()".

It is not consistent. But it is C. :-)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: gmail (figure it out) http://web.torek.net/torek/index.html
Jun 27 '08 #25
In article <67************ *@mid.individua l.net>,
Ian Collins <ia******@hotma il.comwrote:
>If fp is a null pointer, the argument *is* invalid, because fclose requires
fp to be a pointer to a stream that is associated with a file. A null
pointer doesn't qualify, since it is guaranteed not to point to any
object.
>It's a pity that case isn't specified in the way malloc/free is.
The case is different with malloc(). Malloc() can return null
when it succeeds, if its argument is 0.

I believe the requirement for free(0) to work was added at the same
time that malloc(0) was required to work and allowed to return a null
pointer.

-- Richard
--
:wq
Jun 27 '08 #26
In article <fu**********@r egistered.motza rella.org>,
santosh <sa*********@gm ail.comwrote:
>So for the code in question I'd say that conforming compilers are
allowed to do anything since the behaviour is undefined (not explicitly
stated in the standard, but inferred) upon giving fclose an illegal
argument.
The standard *does* say that you get undefined behaviour if you pass
null to a library function expecting a pointer unless it explicitly
says you can. So the behaviour is certainly undefined.

-- Richard
--
:wq
Jun 27 '08 #27
On Sat, 26 Apr 2008 16:21:13 GMT, "Bartc" <bc@freeuk.comw rote in
comp.lang.c:
>
"Richard Heathfield" <rj*@see.sig.in validwrote in message
news:dZ******** *************** *******@bt.com. ..
Bartc said:
This short program:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
int status;

status=fclose(0 );

printf("fclose( 0) status: %d\n",status);

}

crashes on the first two implementations I tried.
The Standard requires that you pass to fclose a pointer to a stream object
of type FILE. You did not do this. (0 doesn't point to any object at all,
let alone a stream object.) You broke the rules, so all bets are off.

fopen() returns a FILE* value, which can include NULL. So it's argueable
that NULL (or (FILE*)NULL) is acceptable, type-wise, to fclose().
There are a large number of standard library functions that accept a
pointer to char, expecting it to be the first character of a '\0'
terminated string. There are also functions in the C standard library
that return a pointer to char on success, but could return NULL,
strchr(), for one. Your suggestion, by analogy, could extend to
saying that all functions expecting a pointer to char should accept a
null pointer.

On the other hand, I think it would have been convenient to specify
that fclose(NULL) would be a no-op, not for the reason that you
mention, but for parity with free(NULL) being defined as a no-op.

As is it, at the end of an operation that allocates one or more
dynamic memory block, and opens one or more files, in a clean up
section that might be reached prematurely if any of the resource
allocations failed, you just have to write:

free (mem1);
free (mem2);
if (file1) fclose(file1);
if (file2) fclose(files):

....which makes the fclose() checking inelegant by comparison. But
such is life.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
Jun 27 '08 #28
Chris Torek wrote:
Eric Sosman <es*****@ieee-dot-org.invalidwrot e:
.... snip ...
>
A burden and a benefit, simultaneously. :-)
>The good idea is not to pass a null pointer in the first place.

And yet, if this is the case, why does free() accept NULL? The
same argument holds here, and -- historically speaking -- at the
time the C89 standard was being created, actual implementations
actually crashed if you called free(NULL). So the committee have
attempted to have it both ways: "We trust you (putting the burden
of checking for NULL first) when you call fclose(), but we do not
trust you (removing the burden of checking for NULL first) when
you call free()".
However fclose doesn't crash on receiving a NULL. It returns EOF.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #29
Joe Wright wrote:
>
.... snip ...
>
I'm not sure it's invalid. Consider..

FILE *fp = fopen("file", "r");

which fails for some reason. Later in the program we do..

int stat = fclose(fp);

The fclose finds that fp does not point to an open file and
returns EOF.
And between fopen and fclose you use the file. If fopen failed it
is not usable, and it does not need closing. The standard says:

7.19.5.1 The fclose function

Synopsis
[#1]
#include <stdio.h>
int fclose(FILE *stream);

Description

[#2] The fclose function causes the stream pointed to by
stream to be flushed and the associated file to be closed.
Any unwritten buffered data for the stream are delivered to
the host environment to be written to the file; any unread
buffered data are discarded. The stream is disassociated
from the file. If the associated buffer was automatically
allocated, it is deallocated.

Returns

[#3] The fclose function returns zero if the stream was
successfully closed, or EOF if any errors were detected.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
6579
by: VB | last post by:
Hi, here File.cpp and File.h: File.cpp: ---------------------- #pragma warning (disable: 4786)
6
5142
by: Jeff | last post by:
If this in not an ANSI-C question, then just flame me and I'll be on my way.... I am using fdopen to associate a FILE with a socket descriptor. (Because I've mentioned a socket descriptor I anticipate the flame. But I believe this is a C question.) My problem is this: if the socket is closed and I pass the FILE returned from fdopen to fclose, my program dies with a memory fault. My question: why do I get a memory fault with fclose when...
10
2018
by: collinm | last post by:
hi is it better to do: FILE *fp; if((fp = fopen(local_led, "r"))!=NULL) { fclose(fp); } else
19
6812
by: lihua | last post by:
Hi, Group! I got one question here: We all know that fclose() must be called after file operations to avoid unexpected errors.But there are really cases when you forget to do that!Just like what happens in memory operations, everyone knows the importance of freeing the allocated memory, but there do have memory leaks from time to
17
14791
by: kathy | last post by:
if fopen failed, does it necessary to call fclose? I see an example like this: .... stream = fopen(...); if(stream == NULL) { .... } else
20
7311
by: David Mathog | last post by:
A program of mine writes to a tape unit. Output can be either through stdout or through a file opened with fopen(). When all the data is transferred to tape the program needs to close the output stream so that the tape driver will write a filemark on the tape. Otherwise multiple clumps of data saved to tape would all appear to be one big file on the tape. When the tape unit device was explicitly opened with fopen() that's possible:...
16
2605
by: Bill Cunningham | last post by:
Is it really necessary to check the return type (int) or fclose ? fopen I can understand but what about using fflsuh(fp); /* fopen's pointer */ fclose(fp); Would that take care of any unforseen truncation ? Bill
0
10453
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10223
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10172
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10003
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6785
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5441
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.