Hello community:
I have been reading source code and documentation of the Mongo C driver recently and noticed an undocumented behavior in bson_copy_value
, which can lead to memory leak when called with incorrect parameters.
To be more specific, bson_copy_value
overwrites memory region pointed to by dst
. If the caller passes a pointer to a bson_value_t
that has already been initialized, the original data , which might contain pointers to allocated buffers (e.g., dst->value.v_utf8.str
, dst->value.v_doc.data
, etc), will be overwritten, causing the buffer to live on heap forever.
A similar pattern exists in bson_copy_to
, which requires the caller to pass an uninitialized bson_t
. If the bson_t
is already initialized and uses the bson_impl_alloc_t
format, the original pointer to the allocated buffer will be lost, leading to memory leakage.
Appending the following line will remove the ambiguity:
dst
MUST be an uninitialized bson_value_t to avoid leaking memory.
Please kindly correctly if I’m wrong!
All the best,
Raymond