Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
C 驱动程序
/ /

bson_t 生命周期

bson_t 可以直接包含其数据,也可以包含指向堆分配内存的指针。覆盖现有的 bson_t 或允许堆栈分配的 bson_t 超出范围可能会导致内存泄漏。 bson_t 应始终使用 bson_destroy 销毁。

用作输出参数的 bson_t 指针必须点新的 bson_t 的有效可覆盖存储,该存储必须是以下之一:

  • bson_t 的未初始化存储。

  • 一个零初始化的 bson_t对象。

  • 使用 初始化的 bson_t对象。BSON_INITIALIZER

  • 不是使用 bson_new 创建的 bson_t对象,而是使用 bson_destroy 销毁的。

这可以在堆栈上:

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!

后退

JSON

在此页面上