Pointer type conversions to char*

6.11 Pointer Type Conversions

Moderators: misra-c, david ward

dcrocker
Posts: 7
Joined: Fri Oct 07, 2005 7:46 pm
Company: Escher Technologies Ltd.
Location: Ash Vale, Surrey, UK
Contact:

Pointer type conversions to char*

Postby dcrocker » Thu Mar 24, 2011 5:15 pm

I have recently come across code similar to the following:

Code: Select all

void serialize(const uint8 data[], size_t length);

int16 myData;
...
serialize((const uint8*)&myData, sizeof(myData));    /* violates MISRA 11.4 */
serialize((const void*)&myData, sizeof(myData));     /* obscures what is going on, but allowed by MISRA */


It seems to me perverse that the first call violates a MISRA rule (even though casting any pointer to a char* does not give rise to alignment issues, see 6.3.4 in the standard), whereas the second contains a potentially dangerous implicit type conversion from void* to another pointer type (imagine that the parameter to serialize had been declared as "const uint32[]" instead).

One possibility is to declare the parameter to serialize as having type const void* instead, but I'm not sure I like this, and it would be necessary to convert it to uint8* anyway inside serialize.

I would prefer to see MISRA C3 amend the rules along the following lines:

1. Explicit casts from an object pointer type to signed or unsigned char* are permitted;

2. Implicit casts from void* to any other type are not permitted. [I don't understand why the MISRA standard ever allowed them.]

3. Maybe a rule along the lines of "A pointer of type void* may only be converted to the same pointer type that it was originally derived from" (with the usual permission to add cv-qualifiers). Perhaps also permitting void* to be converted to signed/unsigned char*.

Any comments?
David Crocker
Escher Technologies Ltd.
http://www.eschertech.com

misra-c
Posts: 547
Joined: Thu Jan 05, 2006 1:11 pm

Re: Pointer type conversions to char*

Postby misra-c » Wed May 25, 2011 2:50 pm

This matter is currently being considered by the working group for treatment in the next release of MISRA C.
---
Posted by and on behalf of
the MISRA C Working Group


Return to “6.11 Pointer Type Conversions”

Who is online

Users browsing this forum: No registered users and 1 guest