You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

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

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)

  • No labels