473,773 Members | 2,334 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
14 1445
James Kanze schrieb:
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.)
Hmm, plausible definition.
>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.)
And that is the point. The standard cannot ensure that a user defined
class constructor initializes all members. E.g. if a pointer member is
not initialized correctly, the assignment operator may fail to cleanup
the old content. On the other side there might be good reasons not to
initialize all PODs of a class in the constructor. So it is always up to
the user to ensure the defined behavior. I would not call it a good
design, when invoking the assignment operator for a default constructed
object is undefined behavior. But the standard does not generally
require defined behavior in this case. In some GUI libraries it is e.g.
required to call some initialization function after the constructor is
called, because some abstract base classes cannot be fully initialized
without the virtual functions of the derived class. Before that
initialization call nearly any other function call is invalid.

>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).
Oh, I always thought that this is some kind of optimization, since
objects in an vector have to be default constructable anyway.
Marcel
Jul 27 '08 #11
On 2008-07-27 07:09:48 -0400, Nick Keighley
<ni************ ******@hotmail. comsaid:
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 .ja.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 i
n
>>practice for double -- because IEEE floating-point, which most modern
computers use, has a notion of "signaling not-a-number" values that cau
se 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
It says that code that your program calls, even if you didn't write it,
can set up trap handlers. That's completely consistent with what I said.

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

Jul 27 '08 #12
On Jul 27, 1:17 pm, Marcel Müller <news.5.ma...@s pamgourmet.com>
wrote:
James Kanze schrieb:
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).
Oh, I always thought that this is some kind of optimization,
since objects in an vector have to be default constructable
anyway.
Since when? All the standard requires is copy constructable and
assignable. (Which is a good thing, because I have some
instances of vectors of objects which are not default
constructable.)

--
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 #13
On Jul 26, 9:08 am, James Kanze <james.ka...@gm ail.comwrote:
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.

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.
Nobody's mentioned this explicitly yet :
AFAIK, it is not undefined to copy the bits
to disk and read them back, even if the variable
is uninitialized. (Of course the value is
still indeterminate after the garbage is read
back from disk).
Jul 27 '08 #14
On Jul 27, 11:42 pm, Old Wolf <oldw...@inspir e.net.nzwrote:
On Jul 26, 9:08 am, James Kanze <james.ka...@gm ail.comwrote:
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.
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.
Nobody's mentioned this explicitly yet :
AFAIK, it is not undefined to copy the bits
to disk and read them back, even if the variable
is uninitialized. (Of course the value is
still indeterminate after the garbage is read
back from disk).
That's a good point. I think it depends on how you do it, but
in most cases, it should be OK. All the C++ standard speaks
about directly is istream::read and ostream::write (and the
streambuf functions they used); for istream, ostream and
streambuf, the interface uses char*, so you're OK. For
wistream, wostream and wstreambuf? A wchar_t can have a
trapping representation. As for fread and fwrite, inherited
from C, they are required to do input and output "as if" using
fgetc and fputc, which means byte access as well (even if they
take a void*), and thus defined behavior.

For anything else, it depends on the implementation, but in
practice, it's hard to imagine a system level read or write
doing anything but byte accesses.

--
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 28 '08 #15

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
1801
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
1792
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
9454
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
10106
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...
0
9914
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
8937
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
6717
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
5355
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...
1
4012
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
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2852
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.