Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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;

Implementation Details

When the following 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

When the 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
bgColor#ffcccc
#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

Code Block

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

Compliant Solution

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

...