Don't Index Out of Bounds in Vector

In the admittedly special case that "position" is equal to the
buffer's size() and "n == 0", then the expression

   &buffer[position]

will index out of bounds.  Use the safer expression

   buffer.data() + position

instead since that's valid when position <= size().

Detected by libstdc++'s debug mode (checked iterators).
This commit is contained in:
Bård Skaflestad
2023-02-08 12:46:41 +01:00
parent 182d58e210
commit e6abb5e3df

View File

@@ -79,7 +79,7 @@ struct Packing<true,T>
std::vector<char>& buffer,
int& position)
{
std::memcpy(&buffer[position], data, n*sizeof(T));
std::memcpy(buffer.data() + position, data, n*sizeof(T));
position += n*sizeof(T);
}
@@ -104,7 +104,7 @@ struct Packing<true,T>
std::vector<char>& buffer,
int& position)
{
std::memcpy(data, &buffer[position], n*sizeof(T));
std::memcpy(data, buffer.data() + position, n*sizeof(T));
position += n*sizeof(T);
}
};