[C-safe-secure-studygroup] MISRA C:2012 Rule 11.6 - can undefined behaviour on conversion from intptr_t/uintptr_t to void * occur?

Martin Sebor msebor at gmail.com
Thu May 31 16:38:54 BST 2018


On 05/31/2018 08:24 AM, Aaron Ballman wrote:
> On Thu, May 31, 2018 at 8:54 AM, Fulvio Baccaglini
> <fulvio_baccaglini at prqa.com> wrote:
>> During the last meeting Aaron raised an interesting query about this
>> first line in the rationale of Rule 11.6:
>> "Conversion of an integer into a pointer to void may result in a pointer
>> that is not correctly aligned, resulting in undefined behaviour."
>>
>> Tentative argument:
>>
>> Looking at the list of undefined behaviours in the C99 standard, this
>> entry looks applicable:
>> [C99-J.2.22] "Conversion between two pointer types produces a result
>> that is incorrectly aligned (6.3.2.3)."
>
> I don't think that's applicable to the MISRA rule at all. The MISRA
> rule is about converting an integer into a pointer (to void or to
> object). C99 6.3.2.3p5 makes this explicitly implementation-defined
> behavior, not undefined behavior. The bullet you found is about
> converting between two pointers and is undefined (though I am not
> certain *why* it's UB to merely form the conversion).

Blame it on trap representations :-)

It's undefined because the source pointer value need not be
representable in the destination pointer type.  For example,
take an implementation where the three least significant bits
in long* are padding bits and only the two least significant
bits in short* are.  On such an implementation directly
converting long* to short* might lose value.  If those bits
were also trapping bits, the conversion would trap.  IMO, even
though implementations with trap representations are exceedingly
rare, I think the undefined behavior here is more useful than
if it were unspecified.  It makes it possible to pinpoint
the source of a misaligned pointer before it is dereferenced
(and either causes a trap then or yields a bogus value).

Martin



More information about the C-safe-secure-studygroup mailing list