Is it undefined behaviour to std::memcpy a struct into a std::vector<char> that has enough capacity?

Viewed 102

Will the following program give undefined behaviour?

#include <vector>
#include <cstring>

struct Data
{
    float   a;
    float   b;
    int     z;
};

int main()
{
    std::vector<char> allMyData;

    Data someStuff({.2f,.3f,1});

    allMyData.resize(sizeof(Data));

    std::memcpy(&allMyData[0], &someStuff, sizeof(Data));

    return 0;
}
2 Answers

There is no undefined behavior in the particular example you have showed. However, things would be quite different if Data contained pointers to external data, or non-POD class types like standard containers, etc.

There is a difference between vector's capacity and its size take for example this code:

auto vector = std::vector<float>();
auto array = std::array<float, 4096>();

array.fill(0.5f);
vector.resize(4096);

std::copy(array.begin(), array.end(), vector.data());

Here copying contents of array like that is perfectly fine because vector's size is 4096 elements - same as array. However, as soon as you do this:

auto vector = std::vector<float>();
auto array = std::array<float, 4096>();

array.fill(0.5f);
vector.reserve(4096);

std::copy(array.begin(), array.end(), vector.data());

You will run into a lot of trouble because even though you copied array into a buffer which can, technically speaking, hold all of the elements, vector does not change its size so vector.empty() would return true and trying to access any of its elements would at best throw a debug exception.

Related