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

Compare with Current View Page History

« Previous Version 25 Next »

Error handling is critical to the success and security of your application. It is necessary to adopt and implement a consistent error handling policy that is consistent with the goals and requirements of your application domain.

Non-Compliant Code Example (Memory Management)

This example, taken from [[MEM32-C. Detect and handle critical memory allocation errors]] demonstrates why checking the return value of memory allocation routines is critical. The buffer input_string is copied into dynamically allocated memory referenced by str. However, the result of malloc() is not checked before str is referenced. Consequently, if malloc() fails, the program will abnormally terminate.

/* ... */
size_t size = strlen(input_string);
if (size == SIZE_MAX) {
  /* Handle Error */
}
str = malloc(size+1);
strcpy(str, input_string);
/* ... */
free(str);

Compliant Solution (Memory Management)

Upon failure, the malloc() function returns NULL. Failing to detect and properly handle this error condition appropriately can lead to abnormal and abrupt program termination.

/* ... */
size_t size = strlen(input_string);
if (size == SIZE_MAX) {
  /* Handle Error */
}
str = malloc(size+1);
if (str == NULL) {
  /* Handle Allocation Error */
}
strcpy(str, input_string);
/* ... */
free(str);

Non-Compliant Code Example (File Operations)

In this example, fopen() is used to open a file for reading. If fopen() is unable to open the file it returns a null pointer. Failing to detect and properly handle this error condition appropriately can lead to abnormal and abrupt program termination.

FILE *fptr = fopen("MyFile.txt","r");

Compliant Solution (File Operations)

To correct this example, the return value of fopen() should be checked for NULL.

FILE *fptr = fopen("MyFile.txt","r");
if (fptr == NULL) {
   /* Handle error condition */
}

This example also applies to recommendation [[FIO04-A. Detect and handle input and output errors]].

Risk Analysis

Failing to detect error condition can result in unexpected program behavior, and possibly abnormal program termination resulting in a denial-of-service condition.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

ERR00-A

2 (medium)

2 (probable)

2 (medium)

P8

L2

Automated Detection

The LDRA tool suite V 7.6.0 is able to detect violations of this recommendation.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

[[Horton 90]] Section 11 p. 168, Section 14 p. 254
[[ISO/IEC 9899-1999]] Sections 7.1.4, 7.9.10.4, and 7.11.6.2
[[Koenig 89]] Section 5.4 p. 73
[[MISRA 04]] Rule 16.1
[[Summit 05]] C-FAQ Question 20.4


13. Error Handling with errno (ERR)      13. Error Handling with errno (ERR)       ERR01-A. Use ferror() rather than errno to check for any accumulated error

  • No labels