C++ Logo


Advanced search

Re: reading values as bytes without memcpu, from enum unsigned char?

From: language.lawyer_at <language.lawyer_at_[hidden]>
Date: Fri, 7 Aug 2020 22:12:22 +0300
>>> Just to spell it out, this is fine:
>>> ```
>>> auto ptr = new AnyType(...);
>>> auto byte_ptr = reinterpret_cast<unsigned char*>(ptr);
>>> *byte_ptr;
>>> ```
>> *byte_ptr; doesn't access anything. lvalue-to-rvalue conversion is not applied to a discarded-value expression of non-volatile type.
>> But anyway, assuming we have access there, that code can haz UB. More specific example:
>> ```
>> int i = UCHAR_MAX + 1;
>> auto uc = *reinterpret_cast<unsigned char*>(&i); // UB because of [expr.pre]/4
>> ```
> I don't see how [expr]/4 applies here. You're accessing an `unsigned
> char` in a place where there is no `unsigned char` object. There's no
> expectation that this value won't be "mathematically defined" or
> otherwise "not in the range of representable values for its type". So
> it's not UB by [expr]/4.

See my analysis of a similar code https://lists.isocpp.org/sg12/2019/06/0802.php

> The issue is that the value is not well-specified by the standard.

The value is 100% specified by the standard. It is the value of `i`, which is `UCHAR_MAX + 1`.

Received on 2020-08-07 14:15:47