You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

In C99, undefined behavior can result when control reaches the end of a non-void function, and the value of the function call is used. This is almost always a programming error, and can lead to unexpected behavior.

This rule is related to MSC01-C. Strive for logical completeness.

Noncompliant Code Example

In this noncompliant code example, control reaches the end of the checkpass() function when the two strings passed to strcmp() are not equal. This leads to undefined behavior, and various compilers generate code equivalent to the checkpass function returning various values when no return checkpass() is reached.

int checkpass(char *password) {
  if (strcmp(password, "pass") == 0) {
    return 1;
  }
}
/* ... */
if (checkpass(userinput)) {
  printf("Success!\n");
}

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

Implementation Details

When this noncompliant code example is compiled with /-Wall on most versions of the GCC compiler,

#include <stdio.h>

int main(void) {
  printf("test\n");
}

the following warning is generated

example.c: In function ‘main’:
example.c:5: warning: control reaches end of non-void function

Compliant Solution

This compliant solution ensures that control never reaches the end of the checkpass function.

int checkpass(char *password) {
  if (strcmp(password, "pass") == 0) {
    return 1;
  }
  return 0;
}
/* ... */
if (checkpass(userinput)) {
  printf("Success!\n");
}

Risk Assessment

Using the return value from a non-void function where control reaches the end of the function can lead to unexpected program behavior, and possibly abnormal program termination.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC37-C

medium

unlikely

low

P6

L2

References

[[ISO/IEC 9899:1999]] Section 6.9.1, "Function definitions"

  • No labels