Failure to specify function prototypes results in a function being implicitly defined. Without a function prototype, the compiler will assume the the correct number and type of parameters have been supplied to a function. This can result in undefined, and perhaps unintended behavior. Given this, functions should always be declared with the appropriate function prototype.
C99 eliminated implicit function declarations from the C language \[[ISO/IEC9899-1999|AA. C References#ISO/IEC 9899-1999]\]. However, many compilers allow compilation of programs containing implicitly defined functions, although they may issue a warning message. These warnings should be resolved \[[MSC00-A|MSC00-A. Compile cleanly at high warning levels]\], but do not prevent program compilation. |
In this example, the definition of func() expects three parameters but is supplied only two. However, because there is no prototype for func(), the compiler assumes that the correct number of arguments has been supplied, and uses the next value on the program stack as the missing third argument.
function(1, 2);
...
int func(int one, int two, int three){
printf("%d %d %d", one, two, three);
return 1;
}
|
To correct this example, the appropriate function prototype for func() should be specified.
int function(int, int, int);
...
function(1,2);
...
int func(int one, int two, int three){
printf("%d %d %d", one, two, three);
return 1;
}
|
The following example is based on rule \[[MEM02-A|MEM02-A. Do not cast the return value from malloc()]\]. The header file {{stdlib.h}} contains the function prototype for {{malloc()}}. Failing to include {{stdlib.h}} causes {{malloc()}} to be implicitly defined. |
char *p = malloc(10); |
including stdlib.h ensures the function prototype for malloc() is declared.
#include <stdlib.h> ... char *p = malloc(10); |
Failure to specify function prototypes can result in undefined, and perhaps unintended program behavior.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
DCL31-C. |
1 (low) |
1 (unlikely) |
3 (low) |
P3 |
L3 |
Examples of vulnerabilities resulting from the violation of this rule can be found on the CERT website.
\[[ISO/IEC9899-1999|AA. C References#ISO/IEC 9899-1999]\] Forward \[[MEM02-A|MEM02-A. Do not cast the return value from malloc()]\], \[[MSC00-A|MSC00-A. Compile cleanly at high warning levels]\] |