945
If a function returns an error, it is important to either fix the problem and try again, alert the user
that an error has happened and let the program continue, or alert the user and close and cleanup
the program.
Phase: Testing
Subject the product to extensive testing to discover some of the possible instances of where/how
errors or return values are not handled. Consider testing techniques such as ad hoc, equivalence
partitioning, robustness and fault tolerance, mutation, and fuzzing.
Demonstrative Examples
Example 1:
The following example attempts to allocate memory for a character. After the call to malloc, an if
statement is used to check whether the malloc function failed.
Example Language: C (Bad)
foo=malloc(sizeof(char)); //the next line checks to see if malloc failed
if (foo==NULL) {
//We do nothing so we just ignore the error.
}
The conditional successfully detects a NULL return value from malloc indicating a failure, however
it does not do anything to handle the problem. Unhandled errors may have unexpected results and
may cause the program to crash or terminate.
Instead, the if block should contain statements that either attempt to fix the problem or notify the
user that an error has occurred and continue processing or perform some cleanup and gracefully
terminate the program. The following example notifies the user that the malloc function did not
allocate the required memory resources and returns an error code.
Example Language: C (Good)
foo=malloc(sizeof(char)); //the next line checks to see if malloc failed
if (foo==NULL) {
printf("Malloc failed to allocate memory resources");
return -1;
}
Example 2:
In the following C++ example the method readFile() will read the file whose name is provided
in the input parameter and will return the contents of the file in char string. The method calls
open() and read() may result in errors if the file does not exist or does not contain any data to
read. These errors will be thrown when the is_open() method and good() method indicate errors
opening or reading the file. However, these errors are not handled within the catch statement.
Catch statements that do not perform any processing will have unexpected results. In this case an
empty char string will be returned, and the file will not be properly closed.
Example Language: C++ (Bad)
char* readfile (char *filename) {
try {
// open input file
ifstream infile;
infile.open(filename);
if (!infile.is_open()) {
throw "Unable to open file " + filename;
}
// get length of file
infile.seekg (0, ios::end);
int length = infile.tellg();
infile.seekg (0, ios::beg);
CWE Version 4.14
CWE-390: Detection of Error Condition Without Action
CWE-390: Detection of Error Condition Without Action