Docs Menu
Docs Home
/ / /
C Driver
/ /

bson_t Lifetimes

On this page

  • bson_t Out Parameters

A bson_t may contain its data directly or may contain pointers to heap-allocated memory. Overwriting an existing bson_t or allowing a stack-allocated bson_t to go out of scope may cause a memory leak. A bson_t should always be destroyed with bson_destroy.

A bson_t pointer used as an out parameter must point to valid overwritable storage for a new bson_t which must be one of:

  • Uninitialized storage for a bson_t.

  • A zero-initialized bson_t object.

  • A bson_t object initialized with BSON_INITIALIZER.

  • A bson_t object not created with bson_new that was destroyed with bson_destroy.

This can be on the stack:

bson_t stack_doc = BSON_INITIALIZER;
example_get_doc (&stack_doc);
bson_destroy (&stack_doc);

Or on the heap:

bson_t *heap_doc = bson_malloc (sizeof (bson_t));
example_get_doc (heap_doc);
bson_destroy (heap_doc);
bson_free (heap_doc);

Omitting bson_destroy in either case may cause memory leaks.

Warning

Passing a bson_t pointer obtained from bson_new as an out parameter will result in a leak of the bson_t struct.

bson_t *heap_doc = bson_new ();
example_get_doc (heap_doc);
bson_destroy (heap_doc); // Leaks the `bson_t` struct!

Back

JSON