From: Nnamdi Date: Wed, 13 Apr 2016 22:04:27 +0000 (+0100) Subject: Stop CreateUninitializedVector returning a pointer to invalid memory. X-Git-Tag: v1.4.0~75^2^2 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=039ab48b7a21ddb8287863883e26bf63a6b6466e;p=platform%2Fupstream%2Fflatbuffers.git Stop CreateUninitializedVector returning a pointer to invalid memory. CreateUninitializedVector was performing the following actions: 1. call StartVector. 2. call make_space, and set buf to point to the reserved space. 3. call EndVector. The problem is that a call to EndVector can ultimately call make_space, which if the buffer is full, will cause a reallocation, invalidating the value stored in buf. So setting buf needs to be delayed until after EndVector. The following code, when run under valgrind shows a write to free'd memory before the change, but no such error after: int main() { flatbuffers::FlatBufferBuilder fbb(128); char *buf = nullptr; fbb.CreateUninitializedVector(128, &buf); *buf = 0; } --- diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index 8e4a796..a33092f 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -1051,8 +1051,11 @@ FLATBUFFERS_FINAL_CLASS uint8_t **buf) { NotNested(); StartVector(len, elemsize); - *buf = buf_.make_space(len * elemsize); - return EndVector(len); + buf_.make_space(len * elemsize); + auto vec_start = GetSize(); + auto vec_end = EndVector(len); + *buf = buf_.data_at(vec_start); + return vec_end; } /// @brief Specialized version of `CreateVector` for non-copying use cases.