...
In this example, the function pointer fn_ptr
is set to refer to strchr()
, which is defined elsewhere. However, because fn_ptr
is declared with an empty parameter type list, the compiler will not generate a warning if the wrong type, or number of arguments are supplied to fn_ptr
. This could result in an unexpected results.
Code Block | ||
---|---|---|
| ||
int add(int x, int y, int z) {
return x + y + z;
}
extern char *strchr();
int (*fn_ptr) ();
int main(void) {
char *c;
fn_ptr = add;
c = fn_ptr("Hello", 'H'); /* incorrect */
/* ... */
return 0;
}
|
Compliant Solution: (function pointers)
To correct this exampleCorrecting this example requires requires two modifications. First, the string.h
header file is included to make the prototype for strchr()
visible to the program. Next, the declaration of fn_ptr
is changed to accept three argumentsbe compatible with strchr()
.
Code Block | ||
---|---|---|
| ||
#include <string.h> int add(int x, int y*fn_ptr) (char *, int z) { return x + y + z; } int main(int argc, char *argv[]void) { intchar (*fn_ptr) (int, int, int) ; int res*c; fn_ptr = add; resc = fn_ptr(2"Hello", 3, 4);'H'); /* incorrect */ /* ... */ return 0; } |
Risk Assessment
...