Rule Definition
The conversion of a function pointer into or from any of:
• Pointer to object;
• Pointer to incomplete;
• void *
results in undefined behaviour.
If a function is called by means of a pointer whose type is not compatible with the called function, the behaviour is undefined. Conversion of a pointer to a function into a pointer to a function with a different type is permitted by The Standard. Conversion of an integer into a pointer to a function is also permitted by The Standard. However, both are prohibited by this rule in order to avoid the undefined behaviour that would result from calling a function using an incompatible pointer type.
Violation Code Sample
typedef void ( *fp16 ) ( int16_t n );
typedef void ( *fp32 ) ( int32_t n );
#include <stdlib.h> /* To obtain macro NULL */
fp32 fp2 = ( fp32 ) fp1; /* Non-compliant - function
* pointer into different
* function pointer */
fp16 fp3 = ( fp16 ) 0x8000; /* Non-compliant - integer into
* function pointer */
fp16 fp4 = ( fp16 ) 1.0e6F; /* Non-compliant - float into
* function pointer */
Fixed Code Sample
fp16 fp1 = NULL; /* Compliant - exception 1 */
if ( fp2 != NULL ) /* Compliant - exception 1 */
{
}
typedef fp16 ( *pfp16 ) ( void );
pfp16 pfp1;
( void ) ( *pfp1 ( ) ); /* Compliant - exception 2 - cast function
* pointer into void
extern void f ( int16_t n );
f ( 1 ); /* Compliant - exception 3 - implicit conversion
* of f into pointer to function */
fp16 fp5 = f; /* Compliant - exception 3
Reference
Standards Reference:
MISRA 2012 C - 11.1: Conversions shall not be performed between a pointer to a function and any other type
MISRA 2008, C++,5-2-6: A cast shall not convert a pointer to a function to any other pointer type, including a pointer to function type.
AUTOSAR 2014, C++, Rule M5-2-6: A cast shall not convert a pointer to a function to any other pointer type, including a pointer to function type.
Related Technologies
Technical Criterion
CWE-704 - Incorrect Type Conversion or Cast
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.