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.
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);
|
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);
|
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");
|
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]\]. |
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 |
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[Horton 90|AA. C References#Horton 90]\] Section 11 p. 168, Section 14 p. 254 \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Sections 7.1.4, 7.9.10.4, and 7.11.6.2 \[[Koenig 89|AA. C References#Koenig 89]\] Section 5.4 p. 73 \[[Summit 05|AA. C References#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