...
This rule is related to MSC01-C. Strive for logical completeness, as both rules involve ensuring that programs properly handle all possible conditions.
Noncompliant Code Example
...
In this noncomplaint code example, control reaches the end of the the getlen()
function when input
does not contain the integer delim
. As the potentially undefined return value of getlen
is later used as an index into an array, this can lead to a buffer overflow.
...
Implementation Details
When a program containing this noncompliant code example is compiled with -Wall
on most versions of the GCC compiler,the following program was compiled with GCC 4.4.3 and run, the getlen
function returned 5, causing to an out of bounds write to the data
array:
Code Block | ||
---|---|---|
| ||
#include <stdio.h> #include <stdlib.h> #include <string.h> size_t getlen(int *input, size_t maxlen, int delim) { size_t i; for (i = 0; i < maxlen; ++i) { if (input[i] == delim) { return i; } } } /* ... */ int main(int argc, char **argv) { size_t i; int data[] = {1, 1, 1}; i = getlen(data, sizeof(data), 0); printf("Returned: %d\n", i); data[i] = 0; return EXIT_SUCCESS; |
When this program is compiled with -Wall
on most versions of the GCC compiler, the following warning is generated
...
Compliant Solution
This compliant solution handles the unexpected situation by immediately terminating the program. The correct changes the interface of getlen
to store the result in a user-provided pointer and return an error code to indicate any error conditions. The best method for handling this type of error is specific to the application and the type of error (see ERR00-C. Adopt and implement a consistent and comprehensive error-handling policy for more on error handling).
Code Block | ||
---|---|---|
| ||
size_tint getlen(int *input, size_t maxlen, int delim, size_t *result) { size_t i; for (i = 0; i < maxlen; ++i) { if (input[i] == delim) { if (result != returnNULL) i;{ } } *result = i; fprintf(stderr, "Fatal error: Invalid input!\n"); /* The abort function terminates the program with SIGABRT. */ abort() } return 0; } } return -1; } /* ... */ size_t i; int data[] = {1, 1, 1}; iif = (getlen(data, sizeof(data), 0); , &i) != 0) { /* Handle error. */ } else { data[i] = userdata; } |
Risk Assessment
Using the return value from a non-void function where control reaches the end of the function can potentially lead to a buffer overflow vulnerability, as well as other unexpected program behavior, and possibly abnormal program terminationbehaviors.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC37-C | high | unlikely | low | P9 | L2 |
...