V591. Non-void function should return a value

31.08.2011

The analyzer detected a function that returns a random value. It might be an error.

Consider this sample:

int main (int argc, char** argv)
{
  ...
  printf("FINISH\r\n");
}

The main() function returns an integer number which is accepted by the calling process. If main() does not return a value explicitly, the calling process gets a nominally undefined value. This is the correct code:

int main (int argc, char** argv)
{
  ...
  printf("FINISH\r\n");
  return retCode;
}

A more interesting and dangerous case is when we deal with code of functions where an undefined value is returned only sometimes. Consider the following sample:

BOOL IsInterestingString(char *s)
{
  if (s == NULL)
    return FALSE;
  if (strlen(s) < 4)
    return;
  return (s[0] == '#') ? TRUE : FALSE;
}

There is a misprint in the code. If a string's length is less than 4 characters, the function will return an undefined value. This is the correct code:

BOOL IsInterestingString(char *s)
{
  if (s == NULL)
    return FALSE;
  if (strlen(s) < 4)
    return FALSE;
  return (s[0] == '#') ? TRUE : FALSE;
}

Note. The analyzer tries to determine cases when absence of a returned value is not an error. Here is an example of code analyzer will consider safe:

int Foo()
{
  ...
  exit(10);
}
You can look at examples of errors from real projects which were detected by this diagnostic message.