Is memcpy-ing a struct into a buffer of uint8_ts and reinterpret-casting it back to struct undefined behaviour?

67 Views Asked by At
#include <iostream>
#include <vector>

struct A
{
    float a = 1;
    float b = 2;
    float c = 3;
};

struct B
{
    float a = 1;
    float b = 2;
};

int main()
{
    uint8_t buffer[5 * sizeof(float)];

    A a0;
    memcpy(buffer, &a0, 3 * sizeof(float));
    A a1 = *reinterpret_cast<A*>(buffer);
    std::cout << a1.a << " " << a1.b << " " << a1.c << '\n';

    int offset = 3;

    B b0;
    memcpy(buffer + offset, &b0, 2 * sizeof(float));
    B b1 = *reinterpret_cast<B*>(buffer + offset);
    std::cout << b1.a << " " << b1.b << " " << '\n';
}

Does the code above have any undefined behaviour? It seems to work fine.

0

There are 0 best solutions below