-
Type:
Task
-
Resolution: Works as Designed
-
Priority:
Minor - P4
-
None
-
Affects Version/s: 1.6.3
-
Component/s: libbson
-
None
-
None
-
None
-
None
-
None
-
None
-
None
-
None
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.