From 79f0df3dfc06d27bf158eedf336a093954dc570f Mon Sep 17 00:00:00 2001 From: emkornfield Date: Thu, 30 May 2019 16:13:34 -0700 Subject: [PATCH] [C++] Fix Undefined behavior for zero length vectors (#5355) * Fix Undefined behavior for zero length vectors * Change fix for UBSan --- include/flatbuffers/flatbuffers.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index 6966cb0af..855abc4df 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -892,10 +892,16 @@ inline voffset_t FieldIndexToOffset(voffset_t field_id) { template const T *data(const std::vector &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) : &v.front(); } template T *data(std::vector &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) : &v.front(); } /// @endcond