Main Content

Call through non-prototyped function pointer

Function pointer declared without its type or number of parameters causes unexpected behavior

Description

This defect occurs when a function without a complete prototype is called using a function pointer.

A function prototype specifies the type and number of parameters.

Risk

Arguments passed to a function without a prototype might not match the number and type of parameters of the function definition, which can cause undefined behavior. If the parameters are restricted to a subset of their type domain, arguments from untrusted sources can trigger vulnerabilities in the called function.

Fix

Before calling the function through a pointer, provide a function prototype.

Examples

expand all

#include <stdio.h>
#include <limits.h>
#define SIZE2 2

typedef void (*func_ptr)();
extern int getchar_wrapper(void);
extern void restricted_int_sink(int i);
/* Integer value restricted to
range [-1, 255] */
extern void restricted_float_sink(double i);
/* Double value restricted to > 0.0 */

                                              

func_ptr generic_callback[SIZE2] =
{
    (func_ptr)restricted_int_sink,
    (func_ptr)restricted_float_sink
};

void func(void)
{
    int ic;
    ic = getchar_wrapper();             
    /* Wrong index used for generic_callback.
	Negative 'int' passed to restricted_float_sink. */
	(*generic_callback[1])(ic); 
}
        
      

In this example, a call through func_ptr passes ic as an argument to function generic_callback[1]. The type of ic can have negative values, while the parameter of generic_callback[1] is restricted to float values greater than 0.0. Typically, compilers and static analysis tools cannot perform type checking when you do not provide a pointer prototype.

Correction — Provide Prototype of Pointer to Function

Pass the argument ic to a function with a parameter of type int, by using a properly prototyped pointer.

#include <stdio.h>
#include <limits.h>
#define SIZE2 2

typedef void (*func_ptr_proto)(int);
extern int getchar_wrapper(void);
extern void restricted_int_sink(int i);
/* Integer value restricted to
range [-1, 255] */
extern void restricted_float_sink(double i);
/* Double value restricted to > 0.0 */                                        

func_ptr_proto generic_callback[SIZE2] =
{
    (func_ptr_proto)restricted_int_sink,
    (func_ptr_proto)restricted_float_sink
};

void func(void)
{
    int ic;
    ic = getchar_wrapper();              
    /* ic passed to function through
properly prototyped pointer. */
	(*generic_callback[0])(ic);
} 

Result Information

Group: Programming
Language: C
Default: On for handwritten code, off for generated code
Command-Line Syntax: UNPROTOTYPED_FUNC_CALL
Impact: Medium

Version History

Introduced in R2017b