1Memory management and reference counting
2===============================================
3
4Due to the nature of its domain, *libcbor* will need to work with heap memory. The stateless decoder and encoder don't allocate any memory.
5
6If you have specific requirements, you should consider rolling your own driver for the stateless API.
7
8Using custom allocator
9^^^^^^^^^^^^^^^^^^^^^^^^
10
11*libcbor* gives you with the ability to provide your own implementations of ``malloc``, ``realloc``, and ``free``. This can be useful if you are using a custom allocator throughout your application, or if you want to implement custom policies (e.g. tighter restrictions on the amount of allocated memory).
12
13In order to use this feature, *libcbor* has to be compiled with the :doc:`appropriate flags </getting_started>`. You can verify the configuration using the ``CBOR_CUSTOM_ALLOC`` macro. A simple usage might be as follows:
14
15.. code-block:: c
16
17	#if CBOR_CUSTOM_ALLOC
18		cbor_set_allocs(malloc, realloc, free);
19	#else
20	   #error "libcbor built with support for custom allocation is required"
21	#endif
22
23.. doxygenfunction:: cbor_set_allocs
24
25
26Reference counting
27^^^^^^^^^^^^^^^^^^^^^
28
29As CBOR items may require complex cleanups at the end of their lifetime, there is a reference counting mechanism in place. This also enables very simple GC when integrating *libcbor* into managed environment. Every item starts its life (by either explicit creation, or as a result of parsing) with reference count set to 1. When the refcount reaches zero, it will be destroyed.
30
31Items containing nested items will be destroyed recursively - refcount of every nested item will be decreased by one.
32
33The destruction is synchronous and renders any pointers to items with refcount zero invalid immediately after calling the :func:`cbor_decref`.
34
35
36.. doxygenfunction:: cbor_incref
37.. doxygenfunction:: cbor_decref
38.. doxygenfunction:: cbor_intermediate_decref
39.. doxygenfunction:: cbor_refcount
40.. doxygenfunction:: cbor_move
41.. doxygenfunction:: cbor_copy
42