Redundant testing by caller and by callee as a style of defensive programming is largely discredited in the C and C++ communities, the main problem being performance. The usual discipline in C and C++ is to require validation on only one side of each interface.
Requiring the caller to validate arguments can result in faster code because the caller may understand certain invariants that prevent invalid values from being passed. Requiring the callee to validate arguments allows the validation code to be encapsulated in one location, reducing the size of the code and making it more likely that these checks are performed in a consistent and correct fashion.
For safety and security reasons, this standard recommends that the called function validate its parameters. Validity checks allow the function to survive at least some forms of improper usage, enabling an application using the function to likewise survive. Validity checks can also simplify the task of determining the condition that caused the invalid parameter.
Noncompliant Code Example
In this noncompliant code example,
usefile() do not validate their parameters. It is possible that an invalid file pointer can be used by the library, corrupting the library's internal state and exposing a vulnerability.
The vulnerability can be more severe if the internal state references sensitive or system-critical data.
Validating the function parameters and verifying the internal state leads to consistency of program execution and may eliminate potential vulnerabilities. In addition, implementing commit or rollback semantics (leaving program state unchanged on error) is a desirable practice for error safety.
Failing to validate the parameters in library functions may result in an access violation or a data integrity violation. Such a scenario indicates a flaw in how the library is used by the calling code. However, the library itself may still be the vector by which the calling code's vulnerability is exploited.
|LANG.STRUCT.UPD||Unchecked parameter dereference|
The validity of parameters must be checked inside each function
Key here (explains table format and definitions)
|CERT C||MSC08-CPP. Functions should validate their parameters||Prior to 2018-01-12: CERT: Unspecified Relationship|
|CWE 2.11||CWE-20, Insufficient input validation||Prior to 2018-01-12: CERT:|
|MITRE CWE||CWE-476||Prior to 2018-01-12:|