...
Code Block | ||||
---|---|---|---|---|
| ||||
#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 | ||||
---|---|---|---|---|
| ||||
#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.
...