Uploaded image for project: 'C Driver'
  1. C Driver
  2. CDRIVER-812

Memory Leak When Using bson_reinit()

    • Type: Icon: Improvement Improvement
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • 1.2.0
    • Affects Version/s: 1.1.10
    • Component/s: docs, libbson
    • Labels:
      None

      The document said:

      The bson_reinit() function shall be equivalent to calling bson_destroy() and bson_init().

      But this demo shows their difference:

      test.cc
      #include <cassert>
      #include <cstring>
      
      #include <mongoc.h>
      
      void log_bson(const bson_t *bson) {
        char *json = bson_as_json(bson, NULL);
        puts(json ? json : "[bson_as_json_error]");
       if (json) bson_free(json);
      }
      
      void fill(bson_t *p1, bson_t *p2) {
        bool status;
        status = bson_append_document_begin(p1, "$set", 4, p2);
        assert(status);
        status = bson_append_bool(p2, "foo", 3, true);
        assert(status);
        status = bson_append_document_end(p1, p2);
        assert(status);
      }
      
      #define USE_BSON_REINIT 1
      
      int main() {
        bson_t bson = BSON_INITIALIZER;
        bson_t child = BSON_INITIALIZER;
        fill(&bson, &child);
        log_bson(&bson);
      
      #if USE_BSON_REINIT
        bson_reinit(&bson);
      #else
        bson_destroy(&bson);
        bson_init(&bson);
      #endif
      
        bson_destroy(&child);
        bson_init(&child);
        fill(&child, &bson);
        log_bson(&child);
        bson_destroy(&bson);
        bson_destroy(&child);
      }
      

      Although outputs are the same when enable and disable USE_BSON_REINIT, valgrind detects a memory leak when USE_BSON_REINIT is true. Something like:

      ==7558== 128 bytes in 1 blocks are definitely lost in loss record 607 of 663
      ==7558==    at 0x4C2B0AF: malloc (vg_replace_malloc.c:296)
      ==7558==    by 0x598260B: bson_malloc (in /usr/lib64/libbson-1.0.so.0.0.0)
      ==7558==    by 0x5976EEC: _bson_grow (in /usr/lib64/libbson-1.0.so.0.0.0)
      ==7558==    by 0x5978307: _bson_append_bson_begin (in /usr/lib64/libbson-1.0.so.0.0.0)
      ==7558==    by 0x108C69: fill(_bson_t*, _bson_t*) (test.cc:14)
      ==7558==    by 0x108DD1: main (test.cc:27)
      

            Assignee:
            jesse@mongodb.com A. Jesse Jiryu Davis
            Reporter:
            mapx Peng Xie
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: