1

I often make mistakes not to initialize the values of the array. Theoretically, we know that in that case, the arrangement should have a waste value.

In practice, however, many values are initialized to zero. Therefore, program satisfied with the small examples. This makes debugging difficult.

Can you tell me why this is happening?

hgmhc
  • 35
  • 3
  • 1
    Does this answer your question? [What happens to a declared, uninitialized variable in C? Does it have a value?](https://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value) – kaylum Jan 02 '21 at 04:16
  • Also take a look here, specifically the section on initializing arrays: https://www.cplusplus.com/doc/tutorial/arrays/ – joshmeranda Jan 02 '21 at 04:17
  • There is no such thing as a "waste value". Accessing the value of an unitialised array element (or variable) gives undefined behaviour - i.e. the relevant C or C++ standard does not define - or even constrain - what happens, so accessing an uninitialised array element may give `0`, or `42`, it may erase your hard drive, or do something else - all those possibilities are correct outcomes according to the standards. Some - but not all - host systems initialise memory to zero before making it available to your program. The real solution is for YOU to ensure ALL variables or arrays are initialised – Peter Jan 02 '21 at 05:09
  • Are you saying that you initialize some values of an array but not all? If that's the case, then any element not explicitly initialized will be set to 0. – dbush Jan 02 '21 at 05:28

2 Answers2

3

Uninitialized values usually appear to be zero in simple test cases because modern operating systems blank memory before handing it to processes as a security precaution. This won't hold if your program has been running for awhile, so don't depend on it. This applies to both automatic (stack) variables and heap allocations. For stack allocations it's actually worse as the variable can take on a value that the variable can't possibly contain normally, potentially crashing your program outright. When dealing with the Itanium processor, it could crash with a memory fault even when assigning an uninitialized integer variable to another variable.

Or try it in DOS. It will not work because DOS doesn't blank memory.

On the other hand, static and global allocations are guaranteed to be zeroed if not initialized by the standard.

Joshua
  • 40,822
  • 8
  • 72
  • 132
0

If you want to be warned about uninitialised memory, both g++ and clang++ support the Memory Sanitizer. Just add -fsanitize=memory to your compiler flags and you'll get runtime errors when you read uninitialised memory.

Matthias Berndt
  • 4,387
  • 1
  • 11
  • 25