Search code examples
c++undefined-behavior

Deal with project which may contain undefined behaviour


I would like advice how to proceed in such situation. Imagine I have large C++ project which works well.

I have suspicion there might be some UB in this code (because in different project written by same author I found UB).

Now, say I need to add new features to this project. I am afraid because:

  • if I recompile with new compiler this can increase risk of UB happening if in the code is UB already. (e.g. new compiler might not be OK with UB which the old compiler was fine with).

Is it realistic to eliminate all UB in this large project by eye inspection (before I move to adding new feature)??

If not, then I should at least compile with same version of compiler right? (to decrease chance of problems if there is UB).

Project is done in Visual Studio so I don't know if there are object files, in which case, I could leave object files same and only modify parts in files where I need to add something - thus again minimizing risk of UB.

What is the course of action in such situation? I think this could be pretty common scenario.


I like suggestion that I test the project using new compiler before adding new code, but even then - we know testing might not reveal UB, isn't it?


Solution

  • As others said: First and foremost, try to find the errors, not hide them.

    1. The first and simplest measure is to set the warning level to /W4 (you can try Wall, but due to the large amount of noise this will produce (e.g. from standard headerfiles), it is usually only of help if you know you have an error in a certain part of your code)
    2. Use static analyzers - you can start with the builtin Code Analysis tool and then go for external tools (which are usually much more difficult to set up correctly for a non-trivial project).
    3. Write lots of tests and make sure, you are exercising edge cases - thats where UB usually lurks.
    4. If possible, try to compile the project (or parts of it) under clang and activate the different sanitizers (in particular there is UndefinedBehaviorSanitizer) which will further instrument your code to check for UB (only helpfull if you have tests to exercise that UB though)
    5. Test your code at different optimization levels and combination of flags (in VS, especially _ITERATOR_DEBUG_LEVEL can be helpfull to find out-of-bounds errors)

    I'd say any non-trivial code base potentially contains undefined behavior. What is special about that particular Programmer? If he/she is prone to a special kind of UB, then you can focus your efforts on this.