Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc, uninitialized global variables

Tags:

c

gcc

Is there any way to know / warn if a global variable is uninitialized with gcc ?

I got it for local/ atomic variables “-Wuninitialized”

like image 221
Kamath Avatar asked Jun 07 '12 07:06

Kamath


People also ask

What are uninitialized global variables?

In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.

What is the value of uninitialized global variable in C?

Global variables get there space in the data segment which is zeroed out. It is not compiler specific but defined in the C standard. So it will always print 0.

What is the default value of a uninitialized global variable?

Default value→ All uninitialized global variables will have 0 as the default value.

Where are the uninitialized global variables stored?

A data segment is a portion of the virtual address space of a program, which contains the global variables and static variables that are initialized by the programmer.


2 Answers

No!
Global and static variables are initialized implicitly if your code doesn't do it explicitly as mandated by the C standard.
In short, global and static variables are never left uninitialized.

like image 55
Alok Save Avatar answered Sep 19 '22 01:09

Alok Save


6.9.2 External object definitions

Semantics

1 If the declaration of an identifier for an object has file scope and an initializer, the declaration is an external definition for the identifier.

2 A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

The above two clauses (from the standard) guarantee that file-scope (global) objects are always initialized.

like image 42
dirkgently Avatar answered Sep 21 '22 01:09

dirkgently