473,766 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

This is undefined, but is it legal?


Hi,

I've heard that if you've declared a variable (such as a double or
an int) and not initialize it, then the result of printing out its
value is undefined.

I've also heard that "undefined behavior" can mean just about
anything, such as "flying monkeys shooting out of your nose." Sure,
that's an exaggeration, but normally I interpret that to mean that the
program can crash (or cease running) erratically, or even corrupt
data.

So my question is: Although I can never safely predict the printed
output of an uninitialized int or double, is it still safe (or legal)
to do so? In other words, if I run this program:

#include <iostream>

int main(int argc, char ** argv)
{
int i;
double d;

std::cout << "i = " << i << std::endl; // safe?
std::cout << "d = " << d << std::endl; // safe?

return 0;
}

I may not be able to predict what will print out, but is there any
chance that the program can crash because of those lines?

If you're curious why I ask this, it's because in some code I'm
working through there is a structure with ints -- some of which are
never used nor initialized. However, this structure (will all its
ints) is getting written out to disk (and later read back in). But at
no time are the values of these uninitialized ints used for logic in
the code.

Because the code is writing out uninitialized values (and later
reading them in), is there a possibility that the program can self-
destruct (or corrupt anything) just because those ints weren't
initialized?

Thanks in advance.

-- Jean-Luc
Jul 25 '08 #1
14 1439
On Fri, 25 Jul 2008 09:04:07 -0700, jl_post wrote:
Hi,

I've heard that if you've declared a variable (such as a double or
an int) and not initialize it, then the result of printing out its value
is undefined.

I've also heard that "undefined behavior" can mean just about
anything, such as "flying monkeys shooting out of your nose."
In fact the commonly acknowledged consequence is that your fridge defrosts.
Sure,
that's an exaggeration, but normally I interpret that to mean that the
program can crash (or cease running) erratically, or even corrupt data.

So my question is: Although I can never safely predict the printed
output of an uninitialized int or double, is it still safe (or legal)
to do so?
It's certainly "legal" in the sense that it won't prevent your program
compiling.
In other words, if I run this program:

#include <iostream>

int main(int argc, char ** argv)
{
int i;
double d;

std::cout << "i = " << i << std::endl; // safe?
std::cout << "d = " << d << std::endl; // safe?

return 0;
}

I may not be able to predict what will print out, but is there any
chance that the program can crash because of those lines?
You're ok. The *value* of the variable i may well be undefined, but
i is nonetheless an int; and outputting an int - any int, whatever its
value - should never crash your program. Ditto double, etc.

--
Lionel B
Jul 25 '08 #2
jl*****@hotmail .com wrote:
[..] So my question is: Although I can never safely predict the printed
output of an uninitialized int or double, is it still safe (or legal)
to do so? In other words, if I run this program:

#include <iostream>
Add

#include <ostream>

to make it completely standard-compliant.
>
int main(int argc, char ** argv)
{
int i;
double d;

std::cout << "i = " << i << std::endl; // safe?
std::cout << "d = " << d << std::endl; // safe?

return 0;
}

I may not be able to predict what will print out, but is there any
chance that the program can crash because of those lines?
[..]
I have never seen 'int' behave that way, but I can attest that an
uninitialised 'double' can cause the system to throw a hardware
exception, and I've seen it happen.

Search the archives for "uninitiali zed value trap exception" or
something like that, and you can hopefully find others' encounters with
pointers and perhaps even integral values.

Generally speaking, any *use* of an uninitialised object has undefined
behaviour.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 25 '08 #3
On Jul 25, 6:04 pm, jl_p...@hotmail .com wrote:
I've heard that if you've declared a variable (such as a
double or an int) and not initialize it, then the result of
printing out its value is undefined.
Anything you do with its *value* is undefined behavior. (You
can still take its address, or assign to it.) With the
exception of unsigned char and char.
I've also heard that "undefined behavior" can mean just about
anything, such as "flying monkeys shooting out of your nose."
Sure, that's an exaggeration, but normally I interpret that to
mean that the program can crash (or cease running)
erratically, or even corrupt data.
In non-priviledged mode, under a modern general purpose OS,
that's what it normally means. On systems without a priviledged
mode (or in kernel code)... I have seen it require the disk to
be reformatted.
So my question is: Although I can never safely predict the
printed output of an uninitialized int or double, is it still
safe (or legal) to do so?
No. It's undefined behavior.
In other words, if I run this program:
#include <iostream>
int main(int argc, char ** argv)
{
int i;
double d;
std::cout << "i = " << i << std::endl; // safe?
std::cout << "d = " << d << std::endl; // safe?
return 0;
}
I may not be able to predict what will print out, but is there
any chance that the program can crash because of those lines?
Of course. It's not likely with int, on most modern machines
(but there is at least one where it is a distinct possibility).
With double, it's possible on every Windows or Unix machine I
know.
If you're curious why I ask this, it's because in some code
I'm working through there is a structure with ints -- some of
which are never used nor initialized. However, this structure
(will all its ints) is getting written out to disk (and later
read back in). But at no time are the values of these
uninitialized ints used for logic in the code.
Because the code is writing out uninitialized values (and
later reading them in), is there a possibility that the
program can self- destruct (or corrupt anything) just because
those ints weren't initialized?
Formally, yes, and any good debugging system will complain. (I
know Purify does, because I've had to deal with the same
problem.) Why don't you just initialize the structs.

And how are you writing them out? If you're just copying the
bits of a struct to disk, then you have no guarantee of being
able to read the data in the future.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jul 25 '08 #4
"Lionel B" <me@privacy.net wrote in message
news:g6******** **@south.jnrs.j a.net...
You're ok. The *value* of the variable i may well be undefined, but
i is nonetheless an int; and outputting an int - any int, whatever its
value - should never crash your program. Ditto double, etc.
Not true. It's not true in theory for int, and definitely not true in
practice for double -- because IEEE floating-point, which most modern
computers use, has a notion of "signaling not-a-number" values that cause a
run-time error condition if accessed.

So even in the simple case where the implementation puts random bits into
uninitialized doubles and does no other checking, it is entirely possible
that those random bits will happen to be a signaling NaN value, which will
cause a run-time exception.

Even for int, there is no reason why an implementation cannot keep track of
whether variables have been initialized, and stop the program if it tries to
access an uninitialized variable. I am not aware of any such
implementations in widespread use today, but they have existed in the past.
Jul 26 '08 #5
On 2008-07-26 10:31:04 -0400, "Andrew Koenig" <ar*@acm.orgsai d:
"Lionel B" <me@privacy.net wrote in message
news:g6******** **@south.jnrs.j a.net...
>You're ok. The *value* of the variable i may well be undefined, but
i is nonetheless an int; and outputting an int - any int, whatever its
value - should never crash your program. Ditto double, etc.

Not true. It's not true in theory for int, and definitely not true in
practice for double -- because IEEE floating-point, which most modern
computers use, has a notion of "signaling not-a-number" values that cause a
run-time error condition if accessed.
My reading of IEEE-754 is that acessing a signaling NaN causes an
invalid operation exception by default, and the result of that
exception is just to return a quite NaN. Unless the program has
installed a trap handler, this is completely innocuous.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Jul 26 '08 #6
Pete Becker wrote:
On 2008-07-26 10:31:04 -0400, "Andrew Koenig" <ar*@acm.orgsai d:
>Not true. It's not true in theory for int, and definitely not true in
practice for double -- because IEEE floating-point, which most modern
computers use, has a notion of "signaling not-a-number" values that
cause a
run-time error condition if accessed.

My reading of IEEE-754 is that acessing a signaling NaN causes an
invalid operation exception by default, and the result of that exception
is just to return a quite NaN. Unless the program has installed a trap
handler, this is completely innocuous.
In theory.
In practice a had a bug in some debug output a few days ago that
accidentally read a double from a union that was initialized as a
pointer. In many cases nothing strange happened. But under some
conditions the whole operating system immediately froze, even when
running in the debugger. I don't know what exception the random bits
caused, but obviously it was strange enough that nobody tested it before.
Marcel
Jul 26 '08 #7
Victor Bazarov wrote:
Generally speaking, any *use* of an uninitialised object has undefined
behaviour.
You should exclude the operations 'taking the address of' and 'creating
a reference to'. They are obviously allowed unless you dereference the
pointers, again except for an assignment.
Strictly speaking this applies to PODs only. However, since C++ objects
usually are valid after construction, they make less trouble unless your
constructor leaves uninitialized members. This should be up to very
basic libraries only. E.g. some std::vector implementations do not
initialize the elements in the range [size(),capacity ()[.
Marcel
Jul 26 '08 #8
On Jul 27, 12:03 am, Marcel Müller <news.5.ma...@s pamgourmet.org>
wrote:
Victor Bazarov wrote:
Generally speaking, any *use* of an uninitialised object has
undefined behaviour.
You should exclude the operations 'taking the address of' and
'creating a reference to'. They are obviously allowed unless
you dereference the pointers, again except for an assignment.
The actual language says that it is using the value of an
uninitialised object which has undefined behavior. Roughly
speaking (or perhaps exactly speaking), it is the lvalue to
rvalue conversion which triggers the undefined behavior. (You
can still assign to the object, for example.)
Strictly speaking this applies to PODs only.
What makes you say that? It applies to everything. (Of course,
a lot of non-POD's have user defined constructors, which take
care of the initialization. But the standard doesn't require
it.)
However, since C++ objects usually are valid after
construction, they make less trouble unless your constructor
leaves uninitialized members. This should be up to very basic
libraries only. E.g. some std::vector implementations do not
initialize the elements in the range [size(),capacity ()[.
Some? The standard doesn't allow them to initialize those
elements (and it doesn't allow you to access them).

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jul 27 '08 #9
On Jul 26, 4:30*pm, Pete Becker <p...@versatile coding.comwrote :
On 2008-07-26 10:31:04 -0400, "Andrew Koenig" <a...@acm.orgsa id:
"Lionel B" <m...@privacy.n etwrote in message
news:g6******** **@south.jnrs.j a.net...
You're ok. The *value* of the variable i may well be undefined, but
i is nonetheless an int; and outputting an int - any int, whatever its
value - should never crash your program. Ditto double, etc.
Not true. *It's not true in theory for int, and definitely not true in
practice for double -- because IEEE floating-point, which most modern
computers use, has a notion of "signaling not-a-number" values that cause a
run-time error condition if accessed.

My reading of IEEE-754 is that acessing a signaling NaN causes an
invalid operation exception by default, and the result of that
exception is just to return a quite NaN. Unless the program has
installed a trap handler, this is completely innocuous.
http://blogs.msdn.com/oldnewthing/ar...3/8682463.aspx

seems to disagree. Or at least trap handlers seem to get enabled
more easily than you'd think on some OSs

--
Nick Keighley
Jul 27 '08 #10

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

Similar topics

7
1493
by: Jim Ford | last post by:
I have the following code: A * F(B * x) { A * y = (A *) *x->data ; return y ; } Is this legal? Do you need more information about the details of the A
8
1639
by: Erik Cato | last post by:
Hi group! Is this code legal? typedef enum { FALSE = 0, TRUE = 1, }t_bool;
24
1800
by: s.subbarayan | last post by:
Dear all, According to standards is this valid: char TmpPtrWriteBuffer; void* PtrWriteBuffer =(void*) TmpPtrWriteBuffer; I had a debate with my colleagues that anything cant be typecasted to void* though the reverse is true.But they said this is valid. I just can't agree with them with out a valid explaination.Can any C standard experts clarify me this?
13
365
by: Kelvin Moss | last post by:
Hi group, In C++ it's undefined behavior if one tries to un-const the constness of a const variable with const_cast<>. I want to know if the same holds good in C too. E.g. const char *s = "abc"; Later, is trying to do (char *) s legal ?
10
1585
by: Kelvin Moss | last post by:
Hi group, In C++ it's undefined behavior if one tries to un-const the constness of a const variable with const_cast<>. I want to know if the same holds good in C too. E.g. const char *s = "abc"; Later, is trying to do (char *) s legal ?
19
1791
by: Sharath A.V | last post by:
I had an argument with someone on wheather this piece of code can invoke undefined bahaviour. I think it does not invoke any undefined behaviour since there is sufficient memory space of 9 integer elements starting from the in the address passed, but the other person insisted that it would invoke undefined behaviour(for whatever reasons he had). void fill(int *p) {
2
1681
by: Army1987 | last post by:
Is this program legal C89? /* no headers included */ int main(void) { if (sizeof (exit(0), 0), ((void (* )(int))&exit)( (puts((const char *)"hello, world"), 0) ), 0) {
6
1843
by: jt | last post by:
#include <stdio.h> void f(); int main() { long int i; i=20; f(); i = 10; printf ("\n%d\n",i);
33
2846
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
9571
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10009
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
9959
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
9838
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
8835
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
7381
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
6651
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
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3532
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.