Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rules for on implicit fields initialization

I have recently fixed a bug in an application of mine: the problem was that an object that resides on the stack had a field left uninitialized.

The object had a class declaration of this type:

struct A{
    int somefield, someotherfield;
    A(): someotherfield(0) {}
}

and when declaring a local variable (like A var; in a function), somefield was left uninitialized, and so a read of it would return a randomish value.

I was certain that fields of a class, which don't appear in the constructor initialization list, would always get initialized by a synthesized trivial constructor (in the case of an int, a zero value). Evidently I am wrong.

So what are the general rules about implicit field initialization?

like image 362
Lorenzo Pistone Avatar asked May 04 '26 03:05

Lorenzo Pistone


1 Answers

  • classes and structs are initialized by contructor
  • Basic types int double char short ... are not initialized and contain random numbers
  • Pointers are not initialized and point to random positions
  • arrays of classes or structs cause each element to be initialized by its constructor
  • arrays of basic types or pointers are random.
like image 176
Totonga Avatar answered May 05 '26 19:05

Totonga