mirror of
https://github.com/google/flatbuffers.git
synced 2026-06-27 19:38:07 +00:00
[C++] Fix Undefined behavior for zero length vectors (#5355)
* Fix Undefined behavior for zero length vectors * Change fix for UBSan
This commit is contained in:
committed by
Wouter van Oortmerssen
parent
9d92fd92e1
commit
79f0df3dfc
@@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user