[CDRIVER-2241] Use a heap allocated bson_t as the 'child' in bson_append_xxx_begin without a memory leak Created: 09/Aug/17  Updated: 27/Oct/23  Resolved: 10/Aug/17

Status: Closed
Project: C Driver
Component/s: libbson
Affects Version/s: 1.6.3
Fix Version/s: None

Type: Task Priority: Minor - P4
Reporter: Weilun Wang Assignee: Unassigned
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Hi guys,

Here is my old code:

int main( int argc, const char** argv )
{
    bson_t * bson = bson_new();
    bson_t * child = bson_new();
 
    bson_append_document_begin(bson, "lalala", 3, child);
    bson_append_document_end(bson, child);
 
    bson_destroy(child);
    bson_destroy(bson);
 
    return 0;
}

When I run it with valgrind, valgrind detects memory leak:

wwang@cadmium:/local/home/wwang/hg/mbuild$ valgrind --tool=memcheck --leak-check=full /with/bb/root/bin/helloworld
......
==23439== HEAP SUMMARY:
==23439==     in use at exit: 128 bytes in 1 blocks
==23439==   total heap usage: 3 allocs, 2 frees, 384 bytes allocated
==23439== 
==23439== 128 bytes in 1 blocks are definitely lost in loss record 1 of 1
==23439==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==23439==    by 0x4E4E659: bson_malloc (in /usr/lib/x86_64-linux-gnu/libbson-1.0.so.0.0.0)
==23439==    by 0x4E4577D: bson_new (in /usr/lib/x86_64-linux-gnu/libbson-1.0.so.0.0.0)
==23439==    by 0x4009D2: main (helloworld.cc:105)
......

I dig in a little. When I do bson_append_document_begin, _bson_append_bson_begin under the hood overwrites the flags of child to set BSON_FLAG_STATIC = 1. Later in bson_destroy, if BSON_FLAG_STATIC is set, bson_free will not be called.

Right now, I am changing my code to:

......
    bson_free(child);
......

No memory leak anymore.

So my questions are:
1. Is this the correct way to use a heap allocated bson_t with any bson_append_xxx_begin functions?
2. If yes, is the description for bson_new(void) misleading?
3. Can you put an example in https://github.com/mongodb/libbson/tree/master/examples as I did a search in github and saw many people are making the same mistakes in their code.



 Comments   
Comment by Hannes Magnusson [ 10/Aug/17 ]

See http://mongoc.org/libbson/current/creating.html#sub-documents-and-sub-arrays

The child should not be allocated as it just points to the correct location in the parent.

See also: http://mongoc.org/libbson/current/bson_append_document_begin.html#description

child MUST be an uninitialized bson_t to avoid leaking memory.

Generated at Wed Feb 07 21:14:37 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.