Many functions will either return a valid value or a value of the correct return type that indicates an error (for example, -1 or a null pointer). It is important that these function return values are checked to ensure that an error has not occurred. Otherwise, unpredictable results are possible.
Non-Compliant Code Example
In this example, input_string
is copied into dynamically allocated memory referenced by str
. However, the result of malloc(input_string_size)
is not checked before str
is referenced. Consequently, if malloc()
fails, the program will abnormally terminate.
char *str = (char*)malloc(strlen(input_string) + 1); strcpy(str, input_string); /* What if malloc() fails? */
Compliant Solution
The malloc()
function, as well as the other memory allocation functions, returns either a null pointer or a pointer to the allocated space. Always test the returned pointer to make sure it is not equal to zero (NULL) before referencing the pointer. Handle the error condition appropriately when the returned pointer is equal to zero.
char *str = (char*)malloc(strlen(input_string) + 1); if (str == NULL) { /* Handle Allocation Error */ } strcpy(str, input_string);
Risk Assessment
Failing to detect error conditions can lead to unpredictable results, including abnormal program termination and denial-of-service attacks or, in some situations, could even allow an attacker to run arbitrary code.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
ERR30-C |
3 (high) |
3 (likely) |
2 (medium) |
P18 |
L1 |
Related Coding Practices
Coding Practice |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
low |
probable |
high |
P2 |
L3 |
|
FLP32-C. Prevent or detect domain and range errors in math functions |
medium |
probable |
medium |
P8 |
L2 |
high |
likely |
medium |
P18 |
L1 |
|
medium |
probable |
high |
P4 |
L3 |
|
FIO33-C. Detect and handle input output errors resulting in undefined behavior |
high |
probable |
medium |
P12 |
L1 |
low |
unlikely |
medium |
P2 |
L3 |
|
ERR00-C. Adopt and implement a consistent and comprehensive error-handling policy |
medium |
probable |
high |
P4 |
L3 |
low |
unlikely |
high |
P1 |
L3 |
|
medium |
probable |
high |
P4 |
L3 |
|
API04-C. Provide a consistent and usable error checking mechanism |
medium |
unlikely |
medium |
P2 |
L3 |
low |
likely |
medium |
P6 |
L2 |
|
low |
likely |
medium |
P6 |
L2 |
References
[[CWE]] CWE-252: Unchecked Error Condition
[[Henricson 97]] Recommendation 12.1 Check for all errors reported from functions
12. Error Handling (ERR) 13. Application Programming Interfaces (API)