bson_t 可以直接包含其数据,也可以包含指向堆分配内存的指针。覆盖现有的 bson_t 或允许堆栈分配的 bson_t 超出范围可能会导致内存泄漏。 bson_t 应始终使用 bson_destroy 销毁。
bson_t 输出参数
用作输出参数的 bson_t 指针必须点新的 bson_t 的有效可覆盖存储,该存储必须是以下之一:
这可以在堆栈上:
bson_t stack_doc = BSON_INITIALIZER; example_get_doc (&stack_doc); bson_destroy (&stack_doc);
或者在堆上:
bson_t *heap_doc = bson_malloc (sizeof (bson_t)); example_get_doc (heap_doc); bson_destroy (heap_doc); bson_free (heap_doc);
在任何一种情况下省略 bson_destroy 都可能导致内存泄漏。
警告
将从 bson_new 获得的 bson_t 指针作为输出参数传递,将导致 bson_t 结构体泄漏。
bson_t *heap_doc = bson_new (); example_get_doc (heap_doc); bson_destroy (heap_doc); // Leaks the `bson_t` struct!