0

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?

Tom Clifford
  • 75
  • 2
  • 7
  • 7
    Uninitialized local non-static variables (including arrays) are really uninitialized. Their values will be *indeterminate* (and seem random). – Some programmer dude Apr 27 '18 at 15:19
  • You could check that excellent answer. It's about a single integer, but it applies to arrays. https://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value – MartinVeronneau Apr 27 '18 at 15:27
  • "*The mistake was that I declared int ndigit[10] but missed the for loop that set all the integers in the array to zero.*" <- no need for a loop, just use `int ndigit[10] = {0};` which forces "default initialization" for all elements you don't provide an initializer for -- aka sets them to `0`. –  Apr 27 '18 at 15:38

1 Answers1

0

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.

nio
  • 5,141
  • 2
  • 24
  • 35
  • 1
    "it will be stored on a stack" is not specified by C. With a sample embedded compiler, `int ndigit[10]` in `main()` is stored with other global variables. It is all compiler dependent., – chux - Reinstate Monica Apr 27 '18 at 16:03