|
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"?
|