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