Next: 3.6.3 Other local operations Up: 3.6 Automatic resource deallocation Previous: 3.6.1 Local image descriptors Contents

## 3.6.2 Local memory allocation

VIPS includes a set of functions for memory allocation local to an image descriptor. The base memory allocation function is `im_malloc()`. It has type:

    char *im_malloc( IMAGE *im, int size )

It operates exactly as the standard `malloc()` C library function, except that the area of memory it allocates is local to image descriptor `im`. If `im_malloc()` is unable to allocate memory, it sets `im_errorstring()` and returns `NULL`. If you pass `NULL` instead of a valid image descriptor, then `im_malloc()` allocates memory globally and you must free it yourself at some stage.

To free memory explicitly, use `im_free()`:

    int im_free( void *mem )

`im_free()` always returns 0, so you can use it as an argument to a callback.

Three macros are defined in `<vips/util.h>` which make memory allocation even easier. `IM_NEW()` allocates a new object. You give it a descriptor and a type, and it returns a pointer to enough space to hold an object of that type. It has type:

    type-name *IM_NEW( IMAGE *im, type-name )

The second macro, `IM_ARRAY()`, is very similar, but allocates space for an array of objects. Note that, unlike the usual `calloc()` C library function, it does not initialise the array to zero. It has type:

    type-name *IM_ARRAY( IMAGE *im,
      int n, type-name )

Finally, `IM_NUMBER()` returns the number of elements in an array of defined size. See the man pages for a series of examples, or see §4.1.

Next: 3.6.3 Other local operations Up: 3.6 Automatic resource deallocation Previous: 3.6.1 Local image descriptors Contents