Search code examples
carraysintkernighan-and-ritchie

What causes these default array values?


I've been working the the Kernighan/Ritchie C Programming Language book (2nd edition) and in the example in chapter 1.6, page 22 I've encountered some strange (to me at least) behaviour based on a mistake I made.

The mistake was that I declared int ndigit[10] but missed the for loop that set all the integers in the array to zero.

The strange thing is the first 8 values in the array seem to work correctly, defaulting to 0, but the last two default to -373429304 and 32766. This resulted in the digit counting function in the program to work as intended apart from the counts of 8s and 9s.

I worked out my mistake and fixed it, but I'm still curious as to why the first 8 values set to 0 but the last two were wildly different?


Solution

  • I will add to the Martin Véronneau's comment with a nice answer,

    What happens to a declared, uninitialized variable in C? Does it have a value?)

    Assumed that you're on x86/x64 PC, if you declare int ndigit[10] inside of a function, and that it is stored on a stack. Stack is a part of a memory, that stores all function calls your program made before, return addresses, parameters to functions and local variables (not dynamically allocated).

    When the function returns, the space is freed by adding a value to a stack pointer. Data in RAM stays there. There were some zero bytes from code execution before not related to your part of code you debugged and something wasn't zeroed which you had observed.