...
In particular, do not default the test for nonzero. For instance, suppose a foo()
function returns 0 to indicate failure or a nonzero value to indicate success. Testing for inequality with zero0,
Code Block | ||||
---|---|---|---|---|
| ||||
if (foo() != 0) ... |
...
despite the convention that 0 indicates failure. Explicitly testing for inequality with zero 0 benefits maintainability if foo()
is later modified to return −1 rather than 0 on failure.
...
In this noncompliant code example, is_banned()
returns zero 0 if false and nonzero if true:
...
Although failures are frequently indicated by a return value of zero0, some common conventions may conflict in the future with code in which the test for nonzero is not explicit. In this case, defaulting the test for nonzero welcomes bugs if and when a developer modifies foo()
to return an error code or −1 rather than 0 to indicate a failure (all of which are also common conventions).
...
Code Block | ||||
---|---|---|---|---|
| ||||
errno_t validateUser(User usr) { if(list_contains(allUsers, usr) == 0) { return 303; //* userUser not found error code */ } if(list_contains(validUsers, usr) == 0) { return 304; //* invalidInvalid user error code */ } return 0; } void processRequest(User usr, Request request) { if(!validateUser(usr)) { return "invalid user"; } serveResults(); } |
...
Code that does not conform to the common practices presented is difficult to maintain. Bugs can easily arise when modifying helper functions that evaluate true/false or success/failure. Bugs can also easily arise when modifying code that tests for equality using a comparison function that obeys the same conventions as standard library functions like such as strcmp
.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP20-C | medium | probable | low | P12 | L1 |
...