[OpenAFS-devel] recent discussions about variable initialization expectations

Nathan Neulinger nneul@umr.edu
12 Apr 2003 12:48:40 -0500


I started looking at a different issue related to this, and finally dug
out the c faq. 

Basically, if a regular function variable, you have to initialize it if
you want it's value to be anything other than garbage. Globals are
initialized to null/zero.


Here's the relevant quote:

1.30:	What am I allowed to assume about the initial values
	of variables which are not explicitly initialized?
	If global variables start out as "zero", is that good
	enough for null pointers and floating-point zeroes?

A:	Uninitialized variables with "static" duration (that is, those
	declared outside of functions, and those declared with the
	storage class static), are guaranteed to start out as zero, as
	if the programmer had typed "= 0".  Therefore, such variables
	are implicitly initialized to the null pointer (of the correct
	type; see also section 5) if they are pointers, and to 0.0 if
	they are floating-point.

	Variables with "automatic" duration (i.e. local variables
	without the static storage class) start out containing garbage,
	unless they are explicitly initialized.  (Nothing useful can be
	predicted about the garbage.)

	Dynamically-allocated memory obtained with malloc() and
	realloc() is also likely to contain garbage, and must be
	initialized by the calling program, as appropriate.  Memory
	obtained with calloc() is all-bits-0, but this is not
	necessarily useful for pointer or floating-point values (see
	question 7.31, and section 5).

	References: K&R1 Sec. 4.9 pp. 82-4; K&R2 Sec. 4.9 pp. 85-86; ISO
	Sec. 6.5.7, Sec. 7.10.3.1, Sec. 7.10.5.3; H&S Sec. 4.2.8 pp. 72-
	3, Sec. 4.6 pp. 92-3, Sec. 4.6.2 pp. 94-5, Sec. 4.6.3 p. 96,
	Sec. 16.1 p. 386.

-- Nathan

------------------------------------------------------------
Nathan Neulinger                       EMail:  nneul@umr.edu
University of Missouri - Rolla         Phone: (573) 341-4841
Computing Services                       Fax: (573) 341-4216