I recently encountered a case where I need to compare two files (golden and expected) for verification of test results and even though the data written to both the files were same, the files does not match.
On further investigation, I found that there is a structure which contains some integers and a char array of 64 bytes, and not all the bytes of char array were getting used in most of the cases and unused fields from the array contain random data and that was causing the mismatch.
This brought me ask the question whether it is good practice to initialize the array in C/C++ as well, as it is done in Java?
It is good practice to initialise memory/variables before you use them – uninitialised variables are a big source of bugs that are often very hard to track down.
Initialising all the data is a very good idea when writing it to a file format: It keeps the file contents cleaner so they are easier to work with, less prone to problems if someone incorrectly tries to “use” the uninitialised data (remember it may not just be your own code that reads the data in future), and makes the files much more compressible.
The only good reason not to initialise variables before you use them is in performance-critical situations, where the initialisation is technically “unnecessary” and incurs a significant overhead. But in most cases initialising variables won’t cause significant harm (especially if they are only declared immediately before they are used), but will save you a lot of development time by eliminating a common source of bugs.