Uninitialized variables may have indeterminate values, as this answer to an earlier question points out. Is there a way to specify this indeterminate data to, say, repeat 0xDEADDEAD
? The indeterminate data is apparently compiler-specific, but it would always be nice to force it to be something easily recognizable.
Are there existing memory leak/corruption detection libraries allowing this? Overloading new
seems like a solution in some cases, but I'd rather not delve into that trickery myself.
The problem is that indeterminate values usually cause undefined behaviour of code, and rarely occurring run time bugs, so, for example, I'd like to spot if I've forgotten a memset()
somewhere in my code. Maybe even randomizing the indeterminate values could serve as a test bench.
In case this is not possible, are there better approaches to solve the problem?
Here are some guidelines for producing good quality C code:
To check the pattern of the value of the variables at runtime is a little bit tricky. As you say, it is compiler/architecture dependent.
Usually static analysis tools can give you warnings about uninitialized variables. Here's a free static code checker that you can play with: cppcheck.
There's indeterminate values, there are memory management errors, and there's the intersection of the two.
I don't know what, if anything C/C++ compilers do for indeterminate values. (A compiler I built for an arguably C like parallel language has an explicit debug switch, that fills every unassigned variable with a value designed to "cause trouble", e.g., for ints, -2^31, for pointers, specific not-void values gauranteed to cause a memory access fault, etc.). I suspect your mileage will vary here by compiler.
Memory management is notoriously hard. In C++ you can use constructors and destructors in a regular way to ensure that many of such errors don't occur, see stackoverflow.com/questions/76796/memory-management-in-c
C is harder, carefully inspecting your code, and ensuring each routine has clear responsibility for either allocation, deallocation or neither will help.
For both C and C++ you can use static analysis tools (Coverity, Fortify) to detect many such allocation errors. Similarly, you can use dynamic analysis tools such as Valgrind, which watches what your object code does and stops it when some memory management errors occur. For C only, you can use our dynamic analysis CheckPointer tool; it will detect all the errors valgrind detects and more (e.g., valgrind can't detect an access outside of a local array [one allocated in your stack]; CheckPointer can).
User contributions licensed under CC BY-SA 3.0