Search code examples
arrayscinteger

Why is an empty integer array filled with seemingly garbage data in C?


I'm currently learning C while following along with The C Book and one of the excercises is to write a program that lets the user input a number, which the program will spit back afterwards.

While troubleshooting my code I noticed that the array I'm putting the digits into is filled with... random data?

enter image description here

This seems weird to me. Is this normal? If so, why does this happen?

Here's my code:

int main() {
    int numbers[20], index;

    index = 0;
    int num = getchar();
    while (num != '\n') {
        numbers[index] = num - 48; // ASCII "0" starts at 48
        index++;
        num = getchar();
    }

    for (int i = 0; i < index; i++) {
        printf("%d", numbers[i]);
    }
    printf("\n");

    return 0;   
}

Solution

  • Static arrays or arrays in global scope will be initialized. Local arrays with automatic storage duration like your numbers are not guaranteed to be initialized and the values they contain are indeterminate. The possibilities include the "garbage" values you're seeing.

    Using these values without initializing them leads to undefined behavior.

    Of note, the real danger here is that they could be what you expect. Maybe you compile in a debug mode and the array does get initialized to contain zeroes. Your program works fine, as far as you can see. Then you compile in a release mode, and code that you thought worked starts exhibiting very odd bugs.

    Compiling with warnings on will help identify sources of undefined behavior. Compiling with warnings as errors will compel you to address the warnings.