unsigned int* v = (unsigned int*)malloc(sizeof(unsigned int) * 100); if(v[0] > 1) printf("boo");These reads can be pretty hard bugs to detect in a lot of cases. Let's look at some tools that can help us find these bugs.
First off, most malloc implementations in debug mode will fill the memory with a special byte pattern like 0xCDCDCDCD. Unfortunately this doesn't directly help you detect reads of such patterns.
The Microsoft Visual C++ compiler has an option /RTCu which checks for use of uninitialised variables at runtime. See 'Run-time error checks'. It only seems to work for stack variables though, and issues no runtime error for the code above.
There is also Address Sanitizer, which is built-in to Visual Studio these days (/fsanitize=address). That also fails to detect the bug, despite it being able to detect a whole lot of other stuff (see https://github.com/google/sanitizers/wiki/addresssanitizer for a list of capabilities)
It looks like Memory Sanitizer will be able to detect this bug, unfortunately this is not built into MSVC, and requires the entire program and all libraries linked to it to be built with Memory Sanitizer as well apparently.
So, that leaves us with good-old Valgrind, which has been around for more than 20 years! The nice thing about Valgrind is that it doesn't require compiling your program in any special way, just run your program from the command line in the usual way, prefixed by the 'valgrind' command. The downsides are it doesn't work on Windows, and it greatly slows down the execution speed of the program (by something like 20x). But it *will* find your read-from-uninitialised-heap-memory bug!
Here's what the Valgrind console output looks like:
==216649== Conditional jump or move depends on uninitialised value(s) ==216649== at 0xA51E40: TestSuite::test() (TestSuite.cpp:133) ==216649== by 0x63E638: main (MainWindow.cpp:4369) ==216649==Wonderful! - what Valgrind is telling us is that the program used some uninitialised data to decide whether to do a jump or not - e.g. if the if() condition was true and the printf should be executed.
In conclusion, to detect reads from uninitialised heap memory, you will need to use either Memory Sanitizer or break out the old workhorse Valgrind.