Is using assert() in C++ bad practice?

C++Coding StyleAssert

C++ Problem Overview


I tend to add lots of assertions to my C++ code to make debugging easier without affecting the performance of release builds. Now, assert is a pure C macro designed without C++ mechanisms in mind.

C++ on the other hand defines std::logic_error, which is meant to be thrown in cases where there is an error in the program's logic (hence the name). Throwing an instance might just be the perfect, more C++ish alternative to assert.

The problem is that assert and abort both terminate the program immediately without calling destructors, therefore skipping the cleanup, whereas throwing an exception manually adds unnecessary runtime costs. One way around this would creating an own assertion macro SAFE_ASSERT, which works just like the C counterpart, but throws an exception on failure.

I can think of three opinions on this problem:

  • Stick to C's assert. Since the program is terminated immediately, it does not matter whether changes are correctly unrolled. Also, using #defines in C++ is just as bad.
  • Throw an exception and catch it in main(). Allowing code to skip destructors in any state of the program is bad practice and must be avoided at all costs, and so are calls to terminate(). If exceptions are thrown, they must be caught.
  • Throw an exception and let it terminate the program. An exception terminating a program is okay, and due to NDEBUG, this will never happen in a release build. Catching is unnecessary and exposes implementation details of internal code to main().

Is there a definitive answer to this problem? Any professional reference?

Edited: Skipping destructors is, of course, no undefined behaviour.

C++ Solutions


Solution 1 - C++

  • Assertions are for debugging. The user of your shipped code should never see them. If an assertion is hit, your code needs to be fixed.

    CWE-617: Reachable Assertion

> The product contains an assert() or similar statement that can be > triggered by an attacker, which leads to an application exit or other > behavior that is more severe than necessary. > > While assertion is good for catching logic errors and reducing the > chances of reaching more serious vulnerability conditions, it can > still lead to a denial of service. > > For example, if a server handles multiple simultaneous connections, > and an assert() occurs in one single connection that causes all other > connections to be dropped, this is a reachable assertion that leads to > a denial of service.

  • Exceptions are for exceptional circumstances. If one is encountered, the user won't be able to do what she wants, but may be able to resume somewhere else.

  • Error handling is for normal program flow. For instance, if you prompt the user for a number and get something unparsable, that's normal, because user input is not under your control and you must always handle all possible situations as a matter of course. (E.g. loop until you have a valid input, saying "Sorry, try again" in between.)

Solution 2 - C++

Assertions are entirely appropriate in C++ code. Exceptions and other error handling mechanisms aren't really intended for the same thing as assertions.

Error handling is for when there's a potential for recovering or reporting an error nicely to the user. For example if there's an error trying to read an input file you may want to do something about that. Errors could result from bugs, but they could also simply be the appropriate output for a given input.

Assertions are for things like checking that an API's requirements are met when the API wouldn't normally be checked, or for checking things the developer believes he's guaranteed by construction. For example if an algorithm requires sorted input you wouldn't normally check that, but you might have an assertion to check it so that debug builds flag that kind of bug. An assertion should always indicate an incorrectly operating program.


If you're writing a program where an unclean shutdown could cause a problem then you may want to avoid assertions. Undefined behavior strictly in terms of the C++ language doesn't qualify as such a problem here, since hitting an assertion is probably already the result of undefined behavior, or the violation of some other requirement which could prevent some clean-up from working properly.

Also if you implement assertions in terms of an exception then it could potentially be caught and 'handled' even though this contradicts the very purpose of the assertion.

Solution 3 - C++

Assertions can be used to verify internal implementation invariants, like internal state before or after execution of some method, etc. If assertion fails it really means the logic of the program is broken and you can't recover from this. In this case the best you can do is to break as soon as possible without passing exception to the user. What is really nice about assertions (at least on Linux) is that core dump is generated as a result of process termination and thus you can easily investigate the stack trace and variables. This is much more useful to understand the logic failure than exception message.

Solution 4 - C++

Not running destructors due to alling abort() is not undefined behaviour!

If it were, then it would be undefined behaviour to call std::terminate() too, and so what would be the point in providing it?

assert() is just as useful in C++ as in C. Assertions are not for error handling, they're for aborting the program immediately.

Solution 5 - C++

IMHO, assertions are for checking conditions that if violated, make everything else nonsense. And therefore you cannot recover from them or rather, recovering is irrelevant.

I would group them into 2 categories:

  • Developer sins (e.g. a probability function that returns negative values ):

> float probability() { return -1.0; }
> > assert(probability() >= 0.0)

  • The Machine is broken (e.g. the machine which runs your program is very wrong):

> int x = 1; > > assert(x > 0);

These are both trivial examples but not too far from reality. For example, think about naive algorithms that return negative indexes for using with vectors. Or embedded programs in custom hardware. Or rather because sh*t happens.

And if there is such development mistakes you should not be confident about any recovering or error handling mechanism implemented. The same applies for hardware errors.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFabian KnorrView Question on Stackoverflow
Solution 1 - C++Kerrek SBView Answer on Stackoverflow
Solution 2 - C++bames53View Answer on Stackoverflow
Solution 3 - C++nogardView Answer on Stackoverflow
Solution 4 - C++Jonathan WakelyView Answer on Stackoverflow
Solution 5 - C++FranMowinckelView Answer on Stackoverflow