Commit 79f0df3d authored by emkornfield's avatar emkornfield Committed by Wouter van Oortmerssen

[C++] Fix Undefined behavior for zero length vectors (#5355)

* Fix Undefined behavior for zero length vectors

* Change fix for UBSan
parent 9d92fd92
...@@ -892,10 +892,16 @@ inline voffset_t FieldIndexToOffset(voffset_t field_id) { ...@@ -892,10 +892,16 @@ inline voffset_t FieldIndexToOffset(voffset_t field_id) {
template<typename T, typename Alloc> template<typename T, typename Alloc>
const T *data(const std::vector<T, Alloc> &v) { const T *data(const std::vector<T, Alloc> &v) {
return v.empty() ? nullptr : &v.front(); // Eventually the returned pointer gets passed down to memcpy, so
// we need it to be non-null to avoid undefined behavior.
static uint8_t t;
return v.empty() ? reinterpret_cast<const T*>(&t) : &v.front();
} }
template<typename T, typename Alloc> T *data(std::vector<T, Alloc> &v) { template<typename T, typename Alloc> T *data(std::vector<T, Alloc> &v) {
return v.empty() ? nullptr : &v.front(); // Eventually the returned pointer gets passed down to memcpy, so
// we need it to be non-null to avoid undefined behavior.
static uint8_t t;
return v.empty() ? reinterpret_cast<T*>(&t) : &v.front();
} }
/// @endcond /// @endcond
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment