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

后端 未结 5 1637
滥情空心
滥情空心 2020-12-23 00:27

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 desi

5条回答
  •  Happy的楠姐
    2020-12-23 00:55

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

提交回复
热议问题