...
Attempting to compile a program with a function declarator that does not include the appropriate type information typically generates a warning but does not prevent program compilation. These warnings should be resolved. (See MSC00-C. Compile cleanly at high warning levels.)
Noncompliant Code Example (Non-Prototype-Format Declarators)
...
Section 6.11.7 of the C Standard [ISO/IEC 9899:2011] states that "the use of function definitions with separate parameter identifier and declaration lists (not prototype-format parameter type and identifier declarators) is an obsolescent feature."
...
Declaring a function without any prototype forces the compiler to assume that the correct number and type of parameters have been supplied to a function. This can result in unintended and undefined behavior.
In this noncompliant code example, the definition of func() in file_a.c expects three parameters but is supplied only two.
...
C99 eliminated implicit function declarations from the C language. However, many compilers still allow the compilation of programs containing implicitly declared functions, although they may issue a warning message. These warnings should be resolved. (See MSC00-C. Compile cleanly at high warning levels.)
Compliant Solution (Function Prototypes)
...
In this noncompliant code example, the function pointer fn_ptr refers to the function add(), which accepts three integer arguments. However, fn_ptr is specified to accept two integer arguments. Setting fn_ptr to refer to add() results in unexpected program behavior. This example also violates DCL35-C. Do not invoke a function using a type that does not match the function definitionCall functions with the correct number and type of arguments.
| Code Block | ||||
|---|---|---|---|---|
| ||||
int add(int x, int y, int z) {
return x + y + z;
}
int main(int argc, char *argv[]) {
int (*fn_ptr) (int, int);
int res;
fn_ptr = add;
res = fn_ptr(2, 3); /* incorrect */
/* ... */
return 0;
}
|
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| 21 S | Fully implemented. | |||||||
GCC |
|
| Can detect violation of this recommendation when the | ||||||
| decltype | Fully implemented. | |||||||
| PRQA QA-C |
| 3335 | Fully implemented. |
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
| ISO/IEC TR 24772 | Type system [IHN] and Subprogram signature mismatch [OTR] |
|---|---|
| MISRA-C | Rule 8.2 |
Bibliography
| [ISO/IEC 9899:2011] | Foreword and Section 6.9.1, "Function Definitions" |
|---|---|
| [Spinellis 2006] | Section 2.6.1, "Incorrect Routine or Arguments" |
...