Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: I added Related Guidelines because pre-book version said "This rule is related to MSC01-C..."

If control reaches the closing curly brace (}) of a non-void function without evaluating a return statement, using the return value of the function call is undefined behavior (see undefined behavior 88).

This rule is related to MSC01-C. Strive for logical completeness because both guidelines are intended to ensure that programs properly handle all possible conditions.

Noncompliant Code Example

...

This error is frequently diagnosed by compilers . (See see MSC00-C. Compile cleanly at high warning levels).)

Compliant Solution

This compliant solution ensures that the checkpass() function always returns a value:

...

This compliant solution 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 see ERR00-C. Adopt and implement a consistent and comprehensive error-handling policy for more on error handling).)

Code Block
bgColor#ccccff
langc
int getlen(const int *input, size_t maxlen, int delim,
           size_t *result) {
  for (size_t i = 0; i < maxlen; ++i) {
    if (input[i] == delim) {
      if (result != NULL) {
        *result = i;
      }
      return 0;
    }
  }
  return -1;
}

void func(int userdata) {
  size_t i;
  int data[] = {1, 1, 1};
  if (getlen(data, sizeof(data), 0, &i) != 0) {
    /* Handle error */
  } else {
    data[i] = userdata;
  }
}

...

MSC37-EX1: According to the C Standard, subclause 5.1.2.2.3, paragraph 1 [ISO/IEC 9899:2011], "reaching Reaching the } that terminates the main function returns a value of 0." As a result, it is permissible for control to reach the end of the main() function without executing a return statement.

...

Using the return value from a non-void function where control reaches the end of the function can lead to a buffer overflow vulnerability vulnerabilities as well as other unexpected program behaviors.

...

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

Related Guidelines

Bibliography

[ISO/IEC 9899:2011]Subclause 5.1.2.2.3, "Program Termination"

...