VLFeat - Documentation > C API

# VLFeat.org

Documentation> C API

- Main Page
- Related Pages
- Data Structures
- Files

Memory and resource handling

Author
  Andrea Vedaldi

Some VLFeat functions return pointers to memory blocks or objects. Only vl_malloc, vl_calloc, vl_realloc and functions whose name contains either the keywords `new` or `copy` transfer the ownership of the memory block or object to the caller. The caller must dispose explicitly of all the resources it owns (by calling vl_free for a memory block, or the appropriate deletion function for an object).

The memory allocation functions can be customized by vl_set_alloc_func (which sets the implementations of vl_malloc, vl_realloc, vl_calloc and vl_free). Remapping the memory allocation functions can be done only if there are no currently allocated VLFeat memory blocks or objects – thus typically at the very beginning of a program. The memory allocation functions are a global property, shared by all threads.

VLFeat uses three rules that simplify handling exceptions when used in combination which certain environment such as MATLAB.

- The library allocates local memory only through the re-programmable vl_malloc, vl_calloc, and vl_realloc functions.
- The only resource referenced by VLFeat objects is memory (for instance, it is illegal for an object to reference an open file). Other resources such as files or threads may be allocated within a VLFeat function call, but they are all released before the function ends, or their ownership is directly transferred to the caller.
- The global library state is an exception. It cannot reference any local object created by the caller and uses the standard C memory allocation functions.

In this way, the VLFeat local state can be reset at any time simply by disposing of all the memory allocated by the library so far. The latter can be done easily by mapping the memory allocation functions to implementations that track the memory blocks allocated, and then disposing of all such blocks. Since the global state does not reference any local object nor uses the remapped memory functions, it is unaffected by such an operation; conversely, since no VLFeat object references anything but memory, this guarantees that all allocated resources are properly disposed (avoiding leaking resource). This is used extensively in the design of MATLAB MEX files (see MATLAB integration).