473,804 Members | 2,148 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 4488
Ian Collins wrote:
CBFalconer wrote:
.... snip ...
>
>However fclose doesn't crash on receiving a NULL. It returns EOF.

Says who? The behaviour is undefined.
Says the standard.

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.

Note the phrase "any errors" in the line above.

--
[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 #41
Richard Heathfield wrote:
>
.... snip ...
>
Undefined behaviour need not have the same effect on my system as
it does on yours. I was under the impression that you already
knew that.
See my reply to Ian.

--
[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 #42
CBFalconer wrote:
Ian Collins wrote:
>CBFalconer wrote:
.... snip ...
>>However fclose doesn't crash on receiving a NULL. It returns EOF.
Says who? The behaviour is undefined.

Says the standard.

Returns

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

Note the phrase "any errors" in the line above.
See Richard's reply to your reply to my reply.

--
Ian Collins.
Jun 27 '08 #43
Richard Tobin wrote:
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.
Okay. I guess it says this somewhere else. IMHO, it should also have
been added to the description of fclose and other functions that are
not defined for a null pointer parameter.

Jun 27 '08 #44
Richard Heathfield wrote:
Ian Collins said:
>Richard Heathfield wrote:
>>la************@ siemens.com said:

Bartc <bc@freeuk.comw rote:
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.
It *is* a good idea:

No, it's merely a useful consequence.

it forces programmers to fix their defective code.

If that were true, it would be a pity that it isn't guaranteed by
the Standard. But it isn't true, of course. Some programmers never
even see the crashes, let alone fix their causes. [example snipped]
Clearly the programmer never bothered to test this execution path,
so he has /not/ been forced to fix his defective code.
But he or she would if a paying customer filed a bug report.

So what you're saying is that the crash in itself is not sufficient to
force the programmer to fix the defective code. This doesn't appear to
contradict anything I said above.
I suppose Larry implied crashes during development and in-house testing.
But a crash isn't guaranteed even in this case. It's merely an outcome
on several common platforms.

Jun 27 '08 #45
CBFalconer wrote:
Ian Collins wrote:
>CBFalconer wrote:
... snip ...
>>
>>However fclose doesn't crash on receiving a NULL. It returns EOF.

Says who? The behaviour is undefined.

Says the standard.

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.

Note the phrase "any errors" in the line above.
Yes. But is it an "error" to pass NULL to fclose? Elsewhere Richard
Tobin says that undefined behaviour is invoked when NULL is passed to a
library function whose definition does not *explicitly* accept NULL as
a valid parameter. The above description of fclose says nothing about a
call with NULL as argument, so presumably, undefined behaviour is
invoked at the point fclose(0) is called. One outcome would be to check
for NULL and return EOF (which DigitalMars seems to do), another would
be to blindly process the argument leading to God knows what.

Jun 27 '08 #46
CBFalconer <cb********@yah oo.comwrites:
Ben Bacarisse wrote:
>>
... snip ...
>>
It's normal. Have you tried strlen(0), strcpy(0, 0) or fopen(0, 0)?
Luck is another matter. In a way you were lucky that at least one
implementati on flagged up the call (with a crash). If you'd used
one that just returns EOF (which is allowed), you'd have no warning
that the construct is not portable.

Sure you would. The EOF is not a normal return value. Something
failed.
So, the poor user writes (and I *know* this is a fragment):

FILE *fp = fopen(argv[1], "r");
if (fp) {
/* ...processing.. . */
}
else fprintf(stderr, "Failed to open %s\n", argv[1]);
if (flose(fp) == EOF)
fprintf(stderr, "Error closing %s\n", argv[1]);

How can they tell, from the EOF return, that their code is not
portable? Note that that is what I claimed. Sure, they get the two
error messages, but they expect that, surely? How does the expected
error return help then to see the non-portability of the construct?

--
Ben.
Jun 27 '08 #47

"Eric Sosman" <es*****@ieee-dot-org.invalidwrot e in message
news:i-*************** *************** @comcast.com...
Bartc wrote:
>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.
I don't think so. My projects require a low-level high-level mainstream
language like C. But there seem to be very few about other than C.

And I'm not going to change language because of some unexpected behaviour in
some library functions, that can be easily fixed with a few lines of code in
wrapper functions that already exist anyway.

I was just surprised at fclose() for example not already doing such a simple
check even if the standard doesn't require it to do so. But clearly it
would upset a lot of people if it were to suddenly behave sensibly.

Pointer values can be roughly grouped into these kinds:

(1) Pointing at the right thing
(2) Pointing at the wrong thing
(3) Containing an illegal address other than NULL
(4) Containing NULL

Of these, I would say (4) is the easiest to verify, and could easily be
placed in a library function. And I would also say it is a common error (to
have NULL where (1) is expected).

(3) is a little more difficult to check, and would probably be unreasonable
to expect most library functions to do so. (Although on some platforms, the
address range 0..N might be known to be invalid, and can be combined with a
check for NULL. This would trap many pointer errors like p+k where p has a
NULL value and k<=N.)

(2) might also be easily checkable in a few cases, for example in a FILE*
value where the beginning of a FILE struct is expected to contain some value
or other.
--
Bartc
Jun 27 '08 #48
Bartc wrote:
Pointer values can be roughly grouped into these kinds:

(1) Pointing at the right thing
(2) Pointing at the wrong thing
(3) Containing an illegal address other than NULL
(4) Containing NULL
I consider object pointer values into a different four groups:
1 address of an object
2 one past the address of an object
3 null pointer
4 indeterminate

--
pete
Jun 27 '08 #49

"pete" <pf*****@mindsp ring.comwrote in message
news:Rp******** *************** *******@earthli nk.com...
Bartc wrote:
>Pointer values can be roughly grouped into these kinds:

(1) Pointing at the right thing
(2) Pointing at the wrong thing
(3) Containing an illegal address other than NULL
(4) Containing NULL

I consider object pointer values into a different four groups:
1 address of an object
2 one past the address of an object
3 null pointer
4 indeterminate
I was thinking in terms of verifying pointer values passed to functions.

(4) of my list is easy. (3) and (2) are progressively more difficult. (1)
might be impossible (for the function to determine anyway).

3 on your list is again easy. But I wouldn't know how to test the others,
and if I did, the object in question might be the wrong one.

--
Bart
Jun 27 '08 #50

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
5143
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
2021
by: collinm | last post by:
hi is it better to do: FILE *fp; if((fp = fopen(local_led, "r"))!=NULL) { fclose(fp); } else
19
6815
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
14793
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
7312
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
2606
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
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10595
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
10343
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
10341
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
10089
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
9171
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5530
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
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4308
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

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.