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

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

Code:
struct TPL_ACTION {
    tpl_action_func action;    /**<  action function pointer   */
};

typedef struct TPL_ACTION tpl_action;

and for instance :

Code:
struct TPL_TASK_ACTIVATION_ACTION {
    /*  base action           */
    tpl_action    b_desc;
    /*  task descriptor pointer     */
    tpl_task      *task;
};

typedef struct TPL_TASK_ACTIVATION_ACTION
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
#2
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
#3
Both Section 6.5.2.2 of \"C89\" (Numbering as in Herbert Schildt's \"The Annotated ANSI C standard\") and ISO/IEC 9899:1999 (E), Section 6.7.2.1, 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.

Regards,

Konrad Schwarz
<t>Konrad Schwarz<br/>
Siemens AG<br/>
CT SE 2 (Corporate Technology, Software & Engineering - Embedded Systems)</t>
#4
konrad.schwarz 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)