MISRA.CAST.OBJ_PTR_TO_INT.2012Conversion performed between a pointer to an object and an integer type.
MISRA C 2012 Rule 11.4: A conversion should not be performed between a pointer to object and an integer typeC90 [Undefined 20; Implementation 24], C99 [Undefined 21, 34; Implementation J.3.7(1)] Category: Advisory Analysis: Decidable, Single Translation Unit Applies to: C90, C99 AmplificationA pointer should not be converted into an integer. An integer should not be converted into a pointer. RationaleConversion of an integer into a pointer to object may result in a pointer that is not correctly aligned, resulting in undefined behaviour. Conversion of a pointer to object into an integer may produce a value that cannot be represented in the chosen integer type resulting in undefined behaviour.
Note: The C99 types intptr_t and uintptr_t, declared in <stdint.h>, are respectively signed and unsigned integer types capable of representing pointer values. Despite this, conversions between a pointer to object and these types is not permitted by this rule because their use does not avoid the undefined behaviour associated with misaligned pointers.
Casting between a pointer and an integer type should be avoided where possible, but may be necessary when addressing memory mapped registers or other hardware specific features. If casting between integers and pointers is used, care should be taken to ensure that any pointers produced do not give rise to the undefined behaviour discussed under Rule 11.3. ExceptionA null pointer constant that has integer type may be converted into a pointer to object. Exampleuint8_t *PORTA = ( uint8_t * ) 0x0002; /* Non-compliant */ uint16_t *p; int32_t addr = ( int32_t ) &p; /* Non-compliant */ uint8_t *q = ( uint8_t * ) addr; /* Non-compliant */ bool_t b = ( bool_t ) p; /* Non-compliant */ enum etag { A, B } e = ( enum etag ) p; /* Non-compliant */ |