Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: fixed implementation details

...

Code Block
bgColor#ffcccc
langc
#include <stddef.h>
 
size_t getlen(const int *input, size_t maxlen, int delim) {
  for (size_t i = 0; i < maxlen; ++i) {
    if (input[i] == delim) {
      return i;
    }
  }
}
 
void func(int userdata) {
  size_t i;
  int data[] = { 1, 1, 1 };
  i = getlen(data, sizeof(data), 0);
  data[i] = userdata;
}

Implementation Details

...

(GCC)

Violating this rule can have  unexpected consequences, as in the following example:

The following program violates this rule:

 

Code Block
bgColor#ffcccc
langc
#include <stdio.h>

size_t getlen(const int *input, size_t maxlen, int delim) {
  for (size_t 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: %zu\n", i);
  data[i] = 0;

  return 0;
}

...

Code Block
example.c: In function 'getlen'€™:
example.c:12: warning: control reaches end of non-void function

When run None of the inputs to the function equal the delimiter, so when run with GCC 4.4.3 on Linux, control reaches the value of i is 5, as if end of the getlen() function returned which returns 5, causing an out-of-bounds write to the data array.

...