Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Correct sections, use abort instead of custom panic function.

...

Code Block
bgColor#ffcccc
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;
    }
  }
}
/* ... */
size_t i;
int data[] = {1, 1, 1};
i = getlen(data, sizeof(data), 0);
data[i] = userdata;

Noncompliant Code Example

Implementation Details

When a program containing this noncompliant code example is compiled with -Wall on most versions of the GCC compiler,This compliant solution handles the unexpected situation by immediately terminating the program. The correct 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
bgColor#ccccff#ffcccc
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;
    }
  }
}
  /* The panic function reports the error and terminates the program. */
  panic("Fatal error: Invalid input!\n");
}
/* ... */
size_t i;
int data[] = {1, 1, 1};
i = getlen(data, sizeof(data), 0);
data[i] = userdata;

Implementation Details

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

the following warning is generated

Code Block

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

Compliant Solution

This compliant solution handles the unexpected situation by immediately terminating the program. The correct 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
bgColor#ccccff
Code Block
bgColor#ffcccc
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;
    }
  }
}

the following warning is generated

Code Block

example.c: In function ‘getlen’:
example.c:12: warning: control reaches end of non-void function  fprintf(stderr, "Fatal error: Invalid input!\n");
  /* The abort function terminates the program with SIGABRT. */
  abort();
}
/* ... */
size_t i;
int data[] = {1, 1, 1};
i = getlen(data, sizeof(data), 0);
data[i] = userdata;

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.

...