Course contentsShow
← C
Lesson 397 of 1,2196. Arrays and StringsFree lesson

The danger of uninitialized arrays

The danger of uninitialized arrays

What you'll learn: Why local arrays start with unpredictable "garbage" values and how to prevent bugs by clearing them.

The hotel room analogy

Imagine checking into a hotel room. When you open the door, you expect the room to be clean and empty, ready for your luggage. In C, declaring a local array is like the operating system handing you a room key. However, C is a "performance-first" language. To save time, it doesn't hire a cleaning crew to scrub the room before you enter.

If you don't explicitly initialize your array, you are walking into a room that might still contain the "trash" left behind by the previous guest—leftover bits of data from other programs that recently occupied that spot in your computer's memory.

Seeing the "garbage" values

When you define an array inside a function, like int scores[5];, C reserves space for five integers but doesn't change the bits already sitting there. If you try to read these values before assigning your own, you will get unpredictable numbers. We call these garbage values.

#include <stdio.h>

int main() {
    // Declaring an array without initializing it
    int myBasket[3];

    printf("What's in my uninitialized basket?\n");
    for(int i = 0; i < 3; i++) {
        // This will print unpredictable, random-looking numbers
        printf("Item %d: %d\n", i, myBasket[i]);
    }

    return 0;
}

If you ran this code, you might see Item 0: 0, Item 1: 32764, and Item 2: -1073741824. Using these numbers in a calculation, like a total sum, would lead to a total disaster.

The safety net: Zero-initialization

To avoid this danger, you should always give your array a starting state. The easiest way to "clean the room" is to use a shortcut that fills the entire array with zeros. By providing just one zero in braces, C assumes you want everything else to be zero too.

int myBasket[3] = {0}; // All 3 elements are now safely set to 0

By making this a habit, you ensure your program’s behavior is predictable and your "basket" is empty before you start adding to it.

Key takeaway

Local arrays are not automatically cleared; always initialize them to {0} to avoid unpredictable "garbage" data.