Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule 45 and polymorphism

I am new to MISRA-C rules and in the code I am working on, there this kind of constructs :

struct TPL_ACTION {
    tpl_action_func action;    /**<  action function pointer   */

typedef struct TPL_ACTION tpl_action;

and for instance :

    /*  base action           */
    tpl_action    b_desc;
    /*  task descriptor pointer     */
    tpl_task      *task;

tpl_task_activation_action ;

tpl_action is an abstract type (no instance) and tpl_task_activation_action is a concrete type.

The function pointed by action function pointer takes a tpl_action * and casts it to the appropriate concrete type.

I understand rule 45 disallows pointer type casting to avoid memory alignment problems but here the first member of the abstract type is of the same type as the first member of the concrete type.

Is it legal ?

Best regards
You are attempting to cast a pointer to one structure to a pointer to a different structure.

This is a violation of rules 45 (MISRA-C:1998) and 11.4 (MISRA-C:2004).
Posted by and on behalf of the MISRA C Working Group
Both Section of \"C89\" (Numbering as in Herbert Schildt's \"The Annotated ANSI C standard\") and ISO/IEC 9899:1999 (E), Section, Paragraph 13, make it clear that the original poster's example is perfectly legal C; no harm can come from using it with any (conforming) C compiler.

The language specifications allow this usage because of its utility---this is how to express polymorphism in C (as the original poster's title implies). Polymorphism is a central tenet of object-oriented programming.

The simplistic formulation of the MISRA rule puts it in the position of preventing object-oriented programming/polymorphism. Strict adherence to the MISRA rule as it stands now requires cumbersome, manual-intensive workarounds. These will be detrimental to MISRA's ultimate goal of preventing software errors.

Perhaps the MISRA committee can be persuaded to rethink this rule in light of its consequences.


Konrad Schwarz
<t>Konrad Schwarz<br/>
Siemens AG<br/>
CT SE 2 (Corporate Technology, Software & Engineering - Embedded Systems)</t>
#4 Wrote:Strict adherence to the MISRA rule as it stands now requires cumbersome, manual-intensive workarounds.

Yes, casting between structure types can be useful in some circumstances, but it can also lead to problems. If you think the benefits for you outweigh the costs then a deviation is the sensible way to deal with this.

Forum Jump:

Users browsing this thread: 1 Guest(s)