Pointer conversions (implicit, explicit, void) - Printable Version +- MISRA Discussion Forums (https://forum.misra.org.uk) +-- Forum: MISRA C (https://forum.misra.org.uk/forumdisplay.php?fid=4) +--- Forum: MISRA-C: 2004 rules (https://forum.misra.org.uk/forumdisplay.php?fid=17) +---- Forum: 6.11 Pointer Type Conversions (https://forum.misra.org.uk/forumdisplay.php?fid=38) +---- Thread: Pointer conversions (implicit, explicit, void) (/showthread.php?tid=901) |
Pointer conversions (implicit, explicit, void) - Gabe - 25-05-2012 I would like to ask for some help interpreting MISRA-C:2004. I have a few very simple examples. Please confirm whether my observations below are correct. 1) #include void main(void) { char* string = "Hello World!"; int* result = string; printf("Result: %d\n", *result); } This code is not MISRA-C:2004 compliant, because the implicit pointer conversion is not legal ANSI C. Thus, it violates rule 1.1. Is this observation correct? 2) #include void main(void) { char* string = "Hello World!"; int* result = (int*)string; printf("Result: %d\n", *result); } This code is MISRA-C:2004 compliant. However, the explicit type cast to int* is a violation of advisory rule 11.4. Is this observation correct? 3) #include void main(void) { char* string = "Hello World!"; void* void_ptr = string; int* result = void_ptr; printf("Result: %d\n", *result); } This code is MISRA-C:2004 compliant. It also does not violate advisory rule 11.4. Is this observation correct? 4) #include void main(void) { char* string = "Hello World!"; void* void_ptr = (void*)string; int* result = void_ptr; printf("Result: %d\n", *result); } This code is MISRA-C:2004 compliant. However, it now does violate advisory rule 11.4 due to the use of the type cast operator. Is this observation correct? I do not see how 3) is better than alternative 2) or 4) above. Double casting through void pointers does not seem to be safe practice. It hides the conversion intent, so it makes the code harder to read. I understand that the main reason for allowing conversions to void pointers is due to legacy reasons (i.e. writing data to memory). Seeing that 11.4 is advisory, would it not be better to refer to "conversions" between different pointers to object, rather than "casting"? Re: Pointer conversions (implicit, explicit, void) - misra-c - 06-06-2012 This reply deals only with the questions of compliance raised in your post. Other non-compliances, such as using are outside the scope of this response. Code that violates a rule may or may not be 'compliant'. As described in Section 4.4, to be compliant, code that violates a rule must be documented and authorised by means of a company-specific procedure. It is therefore easier to talk in terms of whether code violates a given rule rather then whether or not it complies with MISRA C.
This area has received additional treatment in the current draft of the MISRA C:2012 Guidelines. |