55

I've been using std::memcpy to circumvent strict aliasing for a long time.

For example, inspecting a float, like this:

float f = ...;
uint32_t i;
static_assert(sizeof(f)==sizeof(i));
std::memcpy(&i, &f, sizeof(i));
// use i to extract f's sign, exponent & significand

However, this time, I've checked the standard, I haven't found anything that validates this. All I found is this:

For any object (other than a potentially-overlapping subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes ([intro.memory]) making up the object can be copied into an array of char, unsigned char, or std​::​byte ([cstddef.syn]).40 If the content of that array is copied back into the object, the object shall subsequently hold its original value. [ Example:

#define N sizeof(T)
char buf[N];
T obj;                          // obj initialized to its original value
std::memcpy(buf, &obj, N);      // between these two calls to std​::​memcpy, obj might be modified
std::memcpy(&obj, buf, N);      // at this point, each subobject of obj of scalar type holds its original value

— end example ]

and this:

For any trivially copyable type T, if two pointers to T point to distinct T objects obj1 and obj2, where neither obj1 nor obj2 is a potentially-overlapping subobject, if the underlying bytes ([intro.memory]) making up obj1 are copied into obj2,41 obj2 shall subsequently hold the same value as obj1. [ Example:

T* t1p;
T* t2p;
// provided that t2p points to an initialized object ...
std::memcpy(t1p, t2p, sizeof(T));
// at this point, every subobject of trivially copyable type in *t1p contains
// the same value as the corresponding subobject in *t2p

— end example ]

So, std::memcpying a float to/from char[] is allowed, and std::memcpying between the same trivial types is allowed too.

Is my first example (and the linked answer) well defined? Or the correct way to inspect a float is to std::memcpy it into a unsigned char[] buffer, and using shifts and ors to build a uint32_t from it?


Note: looking at std::memcpy's guarantees may not answer this question. As far as I know, I could replace std::memcpy with a simple byte-copy loop, and the question will be the same.

14

3 Answers 3

25

The standard may fail to say properly that this is allowed, but it's almost certainly supposed to be, and to the best of my knowledge, all implementations will treat this as defined behaviour.

In order to facilitate the copying into an actual char[N] object, the bytes making up the f object can be accessed as if they were a char[N]. This part, I believe, is not in dispute.

Bytes from a char[N] that represent a uint32_t value may be copied into an uint32_t object. This part, I believe, is also not in dispute.

Equally undisputed, I believe, is that e.g. fwrite may have written the bytes in one run of the program, and fread may have read them back in another run, or even another program entirely.

Because of that last part, I believe it does not matter where the bytes came from, as long as they form a valid representation of some uint32_t object. You could have cycled through all float values, using memcmp on each until you got the representation you wanted, that you knew would be identical to that of the uint32_t value you're interpreting it as. You could even have done that in another program, a program that the compiler has never seen. That would have been valid.

If from the implementation's perspective, your code is indistinguishable from unambiguously valid code, your code must be seen as valid.

7
  • Separating the single steps involved and qualifying each one as undisputed is making things clear. Jul 12, 2018 at 9:25
  • 3
    What the OP observed is interesting though: While the standard in 6.9.2 explicitly permits copying bytes out of a a trivially copyable object it lacks (or appears to lack -- I just looked at all occurrences of memcpy in n4659) an explicit rule allowing copying bytes into such an object. It is probably considered self-understood; the example in 6.9.2 itself copies the bytes back, after all. Jul 12, 2018 at 9:42
  • 5
    @PeterA.Schneider Right. There is "If the content of that array is copied back into the object, the object shall subsequently hold its original value." which grants permission to copy back into a trivially copyable object, but general permission to copy into (rather than back into) a trivially copyable object is never explicitly given in the standard, it can only be inferred. That's the gist of my answer.
    – user743382
    Jul 12, 2018 at 10:39
  • Good reasoning! I've got a question though. A float -> char[] copy is OK. A char[] -> uint32_t is OK too. But, is a direct float -> uint32_t OK too?
    – geza
    Jul 12, 2018 at 12:17
  • @geza It's iffy, but I'd say that since treating the bytes in that float as a char[] is allowed, when you do a direct float -> uint32_t, in a sense, you are copying from a char[] to a uint32_t.
    – user743382
    Jul 12, 2018 at 12:26
19

Is my first example (and the linked answer) well defined?

The behaviour isn't undefined (unless the target type has trap representations that aren't shared by the source type), but the resulting value of the integer is implementation defined. Standard makes no guarantees about how floating point numbers are represented, so there is no way to extract mantissa etc from the integer in portable way - that said, limiting yourself to IEEE 754 using systems doesn't limit you much these days.

Problems for portability:

  • IEEE 754 is not guaranteed by C++
  • Byte endianness of float is not guaranteed to match integer endianness.
  • (Systems with trap representations).

You can use std::numeric_limits::is_iec559 to verify whether your assumption about representation is correct.

Although, it appears that uint32_t can't have traps (see comments) so you needn't be concerned. By using uint32_t, you've already ruled out portability to esoteric systems - standard conforming systems are not require to define that alias.

34
  • 1
    @StoryTeller as far as I know, unsigned char is the only type guaranteed to not have traps.
    – eerorika
    Jul 12, 2018 at 9:33
  • 2
    @StoryTeller right, so the exact width types aliases have guarantees (beyond tose for the types that they are an alias for, if they alias the standard int or such). That's kinda odd, but it's always nice to be able to ignore traps, so I'll take it :)
    – eerorika
    Jul 12, 2018 at 9:53
  • 2
    "The behaviour isn't undefined". Why? Is there anything in the standard which makes this defined?
    – geza
    Jul 12, 2018 at 10:06
  • 2
    Yes, they give an example what they have previously written in the normative text. I could copy bytes with a simple byte-copy loop, the outcome will be the same. So the point is not memcpy here, but the principle. Can I copy a float to uint32_t byte-by-byte by an means? Is it defined by the standard?
    – geza
    Jul 12, 2018 at 10:55
  • 2
    Many implementations represent certain data types differently in registers and in memory. It is common on 32-bit RISC platforms, for example, that a uint16_t which is placed in a register will have 16 data bits and 16 padding bits which are zeroed when the value is written. If such an object is read when it is uninitialized, it may yield a value which sometimes behaves like it's outside the range 0-65535 but sometimes behaves like it's within that range. Such behavior goes back decades before Itanium.
    – supercat
    Jul 12, 2018 at 20:24
15

Your example is well-defined and does not break strict aliasing. std::memcpy clearly states:

Copies count bytes from the object pointed to by src to the object pointed to by dest. Both objects are reinterpreted as arrays of unsigned char.

The standard allows aliasing any type through a (signed/unsigned) char* or std::byte and thus your example doesn't exhibit UB. If the resulting integer is of any value is another question though.


use i to extract f's sign, exponent & significand

This however, is not guaranteed by the standard as the value of a float is implementation-defined (in the case of IEEE 754 it will work though).

12
  • If we can deduce this from the description of memcpy, then why does the standard highlight the two cases I mentioned in my question?
    – geza
    Jul 12, 2018 at 10:04
  • @geza C++ will rely on C for the definition of memcpy and as I said here it says it copies n bytes "w/o condition" between two objects. Jul 12, 2018 at 13:08
  • Note bit_cast uses memcpy as the underlying type punning mechanism. Jul 12, 2018 at 13:11
  • @ShafikYaghmour: yes, but the problem is not there. For example, if you memcpy a non-trivial copyable type, it is UB, because the standard doesn't allow it. Like it doesn't allow my example explicitly.
    – geza
    Jul 12, 2018 at 13:15
  • @ShafikYaghmour: it's not a problem. A compiler provided library can use any UB it wants, see my comment below the question.
    – geza
    Jul 12, 2018 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.