473,698 Members | 2,080 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

undefined behaviour?

I stumbled upon the following code (stripped to the minimum)
#include <stdio.h>
#include <stdlib.h>

int main(void){

char *file_name = "t1.txt";
char ch;
FILE *pf = fopen(file_name , "r+");
fputs("bla", pf);
ungetc('z', pf);
ch = getc(pf);
printf("ch = %c\n", ch);
fclose(pf);
return 0;
}

Now I'm wondering if this is defined behaviour or not, and if it's
defined should there be a problem with the close at the end?

Thanks in advance
Friedrich

--
Please remove just-for-news- to reply via e-mail.
Dec 15 '05
20 1315
Friedrich Dominicus <ju************ *****@q-software-solutions.de> wrote:
I stumbled upon the following code (stripped to the minimum)
#include <stdio.h>
#include <stdlib.h>

int main(void){

char *file_name = "t1.txt";
char ch;
FILE *pf = fopen(file_name , "r+");
fputs("bla", pf);
ungetc('z', pf);


Yes, undefined behaviour. You just wrote (using fputs()) to an update
stream, causing it to be set to output mode. ungetc() expects an input
stream. You cannot use ungetc() on an output-oriented update stream
without first using fflush() or a file positioning function.

This raises the question of what happens when you fflush() between
fputs() and ungetc(). AFAICT, that should work, not cause UB, cause the
'z' to be read by the following getc(), and as the Standard says about
ungetc(): "The external storage corresponding to the stream is
unchanged".

Richard
Dec 15 '05 #11
Jordan Abel wrote:
On 2005-12-15, santosh <sa*********@gm ail.com> wrote:
char *file_name = "t1.txt";

An uninitialised pointer is being used here.


The line you are responding to is a declaration, and, moreover, one with
an initializer.

You claim that on your implementation the program crashes on that line.
Either you're lying, or you have a very crappy [and non-conforming]
implementation.


Your right. I'm sorry. It was an incredible oversight on my part.

That being said, the code as was posted did crash over here.
The compiler is gcc (mingw).
After I introduced error checking for each function call I found that
the
first error was with foen().
I modified "r+" to "w+" which succeeded, but then ungetc() returned
EOF.
I corrected that by inserting a 'fflush(pf)' before calling ungetc().
Then it was getc()'s turn to return EOF.
After I changed 'ch' from char to int the program finally executed as
it
should. The contents of the file after running the code is:
bla [Hex dump = 626c 610d 0a]

Dec 15 '05 #12
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Friedrich Dominicus <ju************ *****@q-software-solutions.de> wrote:
I stumbled upon the following code (stripped to the minimum)
#include <stdio.h>
#include <stdlib.h>

int main(void){

char *file_name = "t1.txt";
char ch;
FILE *pf = fopen(file_name , "r+");
fputs("bla", pf);
ungetc('z', pf);
Yes, undefined behaviour. You just wrote (using fputs()) to an update
stream, causing it to be set to output mode. ungetc() expects an input
stream.

Well that's what the 'r' is for or not? So for me it's an input stream
in first line and writable also.
You cannot use ungetc() on an output-oriented update stream
without first using fflush() or a file positioning function.

As posted before I can understand this argument, and as said before I
have found it out there, but was puzzling about its validity.

Regards
Friedrich
--
Please remove just-for-news- to reply via e-mail.
Dec 15 '05 #13
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:

This raises the question of what happens when you fflush() between
fputs() and ungetc(). AFAICT, that should work, not cause UB, cause the
'z' to be read by the following getc(), and as the Standard says about
ungetc(): "The external storage corresponding to the stream is
unchanged".

So I'd argue it's defined if there is an fflush between the fputs and
ungetc, and undefined without it. That's sounds reasonable

Regards
Friedrich
--
Please remove just-for-news- to reply via e-mail.
Dec 15 '05 #14

Friedrich Dominicus wrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Friedrich Dominicus <ju************ *****@q-software-solutions.de> wrote:
I stumbled upon the following code (stripped to the minimum)
#include <stdio.h>
#include <stdlib.h>

int main(void){

char *file_name = "t1.txt";
char ch;
FILE *pf = fopen(file_name , "r+");
fputs("bla", pf);
ungetc('z', pf);


Yes, undefined behaviour. You just wrote (using fputs()) to an update
stream, causing it to be set to output mode. ungetc() expects an input
stream.

Well that's what the 'r' is for or not? So for me it's an input stream
in first line and writable also.
You cannot use ungetc() on an output-oriented update stream
without first using fflush() or a file positioning function.

As posted before I can understand this argument, and as said before I
have found it out there, but was puzzling about its validity.


Here is the appropriate section of the Standard (n1124 to be exact):

7.19.5.3p6

When a file is opened with update mode ('+' as the second or third
character in the
above list of mode argument values), both input and output may be
performed on the
associated stream. However, output shall not be directly followed by
input without an
intervening call to the fflush function or to a file positioning
function (fseek,
fsetpos, or rewind), and input shall not be directly followed by output
without an
intervening call to a file positioning function, unless the input
operation encounters endof-
file. Opening (or creating) a text file with update mode may instead
open (or create) a
binary stream in some implementations .

I hope that relieves any doubt you had about the validity of the
statements made to that effect here.

Robert Gamble

Dec 15 '05 #15
"santosh" <sa*********@gm ail.com> writes:
Jordan Abel wrote:
On 2005-12-15, santosh <sa*********@gm ail.com> wrote:
>> char *file_name = "t1.txt";
> An uninitialised pointer is being used here.
The line you are responding to is a declaration, and, moreover, one with
an initializer.

You claim that on your implementation the program crashes on that line.
Either you're lying, or you have a very crappy [and non-conforming]
implementation.


Your right. I'm sorry. It was an incredible oversight on my part.

That being said, the code as was posted did crash over here.
The compiler is gcc (mingw).
After I introduced error checking for each function call I found that
the
first error was with foen().

Well that does not mean that the code as given was invalid
I modified "r+" to "w+" which succeeded, but then ungetc() returned
EOF. That's interesting and I think that should not happen, even if you use
"r+". I corrected that by inserting a 'fflush(pf)' before calling
ungetc(). I'd argue this is the real problem.

The system as used her has worked fine but baild out on the fclose at
the end. After insering the fflush here this was gone and the result
were as expected.
After I changed 'ch' from char to int the program finally executed as
it I don't think this is really a problem. should. The contents of the file after running the code is:

Can't tell I did not care about the content just the fputs + ungetc
stuff. However thanks for taking the time checking all this "stuff"

Regards
Friedrich

--
Please remove just-for-news- to reply via e-mail.
Dec 15 '05 #16
"Robert Gamble" <rg*******@gmai l.com> writes:
Here is the appropriate section of the Standard (n1124 to be exact):

7.19.5.3p6

When a file is opened with update mode ('+' as the second or third
character in the
above list of mode argument values), both input and output may be
performed on the
associated stream. However, output shall not be directly followed by
input without an
intervening call to the fflush function or to a file positioning
function (fseek,
fsetpos, or rewind), and input shall not be directly followed by output
without an
intervening call to a file positioning function, unless the input
operation encounters endof-
file. Opening (or creating) a text file with update mode may instead
open (or create) a
binary stream in some implementations .

I hope that relieves any doubt you had about the validity of the
statements made to that effect here.


Well that is the "definitive " answer for me. I have not seen
it. Thanks for pointing it out to me.

Regards
Friedrich
--
Please remove just-for-news- to reply via e-mail.
Dec 15 '05 #17
santosh wrote:
Friedrich Dominicus wrote:

ungetc('z', pf);

The first parameter of ungetc() is an int.


and 'z' *is* an int
--
Nick Keighley

Dec 15 '05 #18
"Nick Keighley" <ni************ ******@hotmail. com> writes:
santosh wrote:
Friedrich Dominicus wrote:

> ungetc('z', pf);

The first parameter of ungetc() is an int.


and 'z' *is* an int


And even if it weren't, it would be implicitly converted to int (since
there's a "#include <stdio.h>").

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 15 '05 #19
On Thu, 15 Dec 2005 16:14:21 +0100, in comp.lang.c , Friedrich
Dominicus <ju************ *****@q-software-solutions.de> wrote:
You cannot use ungetc() on an output-oriented update stream
without first using fflush() or a file positioning function.
As posted before I can understand this argument, and as said before I
have found it out there, but was puzzling about its validity.


Its in the Standard.

7.19.5.3(6) When a file is opened with update mode ... output shall
not be directly followed by input without an intervening call to the
fflush function or to a file positioning function..., and input shall
not be directly followed by output without an intervening call to a
file positioning function...

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 15 '05 #20

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

Similar topics

6
2143
by: Simon Bailey | last post by:
In the following code at the end of the program z = 20 & y = 99. void doit(const int* x) { int* nonconst; nonconst = const_cast<int*>(x); *nonconst = 99; } int main(int argc, char* argv)
8
4582
by: Scott J. McCaughrin | last post by:
The following program compiles fine but elicits this message from the linker: "undefined reference to VarArray::funct" and thus fails. It seems to behave as if the static data-member: VarArray::funct were an extern, but it is declared in the same file (q.v.). What is the remedy for this? =================
8
1815
by: Joona I Palaste | last post by:
We all know that this: void *p; if (p=malloc(1)) { free(p); p; } causes undefined behaviour if malloc() succeeds. But what about this?
25
3089
by: Nitin Bhardwaj | last post by:
Well, i'm a relatively new into C( strictly speaking : well i'm a student and have been doing & studying C programming for the last 4 years).....and also a regular reader of "comp.lang.c" I don't have a copy of ANSI C89 standard,therefore i had to post this question: What is the difference between "unspecified" behaviour & "undefined" behaviour of some C Code ??
23
3201
by: Ken Turkowski | last post by:
The construct (void*)(((long)ptr + 3) & ~3) worked well until now to enforce alignment of the pointer to long boundaries. However, now VC++ warns about it, undoubtedly to help things work on 64 bit machines, i.e. with 64 bit pointers. In the early days of C, where there were problems with the size of int being 16 or 32 bits, the response was that an int was guaranteed to hold a pointer (yes, there were 64Kb address spaces at one time!)....
12
1803
by: RoSsIaCrIiLoIA | last post by:
On Mon, 07 Feb 2005 21:28:30 GMT, Keith Thompson <kst-u@mib.org> wrote: >"Romeo Colacitti" <wwromeo@gmail.com> writes: >> Chris Torek wrote: >>> In article <4205BD5C.6DC8@mindspring.com> >>> pete <pfiland@mindspring.com> wrote: > >>> >If you have >>> > int array; >>> >then
26
2182
by: Frederick Gotham | last post by:
I have a general idea of the different kinds of behaviour described by the C Standard, such as: (1) Well-defined behaviour: int a = 2, b = 3; int c = a + b; (Jist: The code will work perfectly.)
12
5670
by: Franz Hose | last post by:
the following program, when compiled with gcc and '-std=c99', gcc says test.c:6: error: jump into scope of identifier with variably modified type that is, it does not even compile. lcc-win32, on the other hand, reports Warning test.c: 7 unreachable code
10
1797
by: subramanian100in | last post by:
Consider the following code: #include <iostream> #include <cstdlib> using namespace std; int main() { const double& ref = 100;
33
2826
by: coolguyaroundyou | last post by:
Will the following statement invoke undefined behavior : a^=b,b^=a,a^=b ; given that a and b are of int-type ?? Be cautious, I have not written a^=b^=a^=b ; which, of course, is undefined. I am having some confusion with the former statement! Also, state the reason for the statement being undefined!
0
8600
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,...
1
8892
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
8860
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
7712
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...
1
6518
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5860
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
4614
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3038
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
3
1998
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.