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

  • 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.)

Leave a Comment

tech