This guideline has not been reviewed recently and may be outdated. Please review it and comment to reflect any newly available information.
Some functions, especially those originally specified for the C Language, 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.
Compliant Solution 1
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.
Compliant Solution 2
A better approach is to use C++ facilities that throw exceptions, rather than those that use error codes. For example, it is better to use
new rather than the
malloc series of memory allocation functions.
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.
|Ignored return value|
|LDRA tool suite||9.7.1|
382 S, 121 D, 122 D