C++ Default Initialization | Uninitialized Locals and Undefined Behavior

C++ Default Initialization | Uninitialized Locals and Undefined Behavior

이 글의 핵심

Default initialization means no initializer: local ints can hold garbage. Globals are different. Use value initialization or member defaults to stay safe.

What is default initialization?

Declaring a variable without an initializer applies default initialization. For local scalars, the value can be indeterminate—reading it is undefined behavior. Prefer value initialization (T{}) or explicit assignment.

int x;        // default-initialized local: garbage
int y = 10;   // explicit

Scalars (automatic storage)

void func() {
    int x;       // indeterminate
    double d;    // indeterminate
    int* ptr;    // indeterminate
    
    x = 10;
    d = 3.14;
    ptr = nullptr;
}

Undefined behavior examples

Using x before assignment in conditions, arithmetic, or I/O is UB.

Pitfalls

Missing sum initialization

// ❌
int sum;
for (int i = 0; i < 10; i++) {
    sum += i;  // UB
}

// ✅
int sum = 0;

Uninitialized pointers

int* ptr = nullptr;

Class members

class Good {
    int value = 0;
public:
    Good() = default;
};

Conditional assignment

Initialize before the branch or set a default first.

memset anti-pattern

Do not memset non-trivial C++ objects to zero—use value initialization, ctors, or member defaults.

FAQ

Q1: What is default initialization?
A: No initializer—dangerous for local scalars.

Q2: Globals?
A: Static storage is zero-initialized first, then dynamic init.

Q3: Fix?
A: Always initialize—=, {}, or member defaults.

Related: Value initialization, Zero initialization, Undefined behavior.


  • C++ Value initialization
  • C++ Zero initialization
  • C++ Undefined behavior

Keywords

C++, default initialization, undefined behavior, uninitialized variable.


  • C++ Copy initialization
  • C++ Dynamic initialization