Main Content

Unreliable cast of function pointer

Function pointer cast to another function pointer with different argument or return type

Description

This defect occurs when a function pointer is cast to another function pointer that has different argument or return type.

Risk

If you cast a function pointer to another function pointer with different argument or return type and then use the latter function pointer to call a function, the behavior is undefined.

Fix

Avoid a cast between two function pointers with mismatch in argument or return types.

See examples of fixes below.

If you do not want to fix the issue, add comments to your result or code to avoid another review. See:

Examples

expand all

#include <stdio.h>
#include <math.h>
#define PI 3.142
 
double Calculate_Sum(int (*fptr)(double))
{
    double  sum = 0.0;
    double  y;
	  
    for (int i = 0;  i <= 100;  i++)
    {
        y = (*fptr)(i*PI/100);
        sum += y;
    }
    return sum / 100;
}
 
int main(void)
{
    double  (*fp)(double);      
    double  sum;
 
    fp = sin;
    sum = Calculate_Sum(fp); 
    /* Defect: fp implicitly cast to int(*) (double) */

    printf("sum(sin): %f\n", sum);
    return 0;
}

The function pointer fp is declared as double (*)(double). However in passing it to function Calculate_Sum, fp is implicitly cast to int (*)(double).

Correction — Avoid Function Pointer Cast

One possible correction is to check that the function pointer in the definition of Calculate_Sum has the same argument and return type as fp. This step makes sure that fp is not implicitly cast to a different argument or return type.

#include <stdio.h>
#include <math.h>
# define PI 3.142
 
/*Fix: fptr has same argument and return type everywhere*/
double Calculate_Sum(double (*fptr)(double)) 
{
    double  sum = 0.0;
    double y;
	    
    for (int i = 0;  i <= 100;  i++)
    {
        y = (*fptr)(i*PI/100);
        sum += y;
    }
    return sum / 100;
}
 
int main(void)
{
    double  (*fp)(double);      
    double  sum;
 
    
    fp = sin;
    sum = Calculate_Sum(fp);
    printf("sum(sin): %f\n", sum);
 
    return 0;
}

Result Information

Group: Static memory
Language: C | C++
Default: On
Command-Line Syntax: FUNC_CAST
Impact: Medium

Version History

Introduced in R2013b