next up previous contents
Next: 2.3 Output to an Up: 2. Programming WIO operations Previous: 2.1 Input from an   Contents

2.2 Memory allocation

VIPS includes some functions to help you allocate memory for objects, and to guarantee that objects are eventually freed. The base memory allocation function is im_malloc(). It has type:

void *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, that is, when descriptor im is closed, the memory will automatically be freed for you. Memory is freed in reverse order to the order in which it was allocated; see §3.6.

If im_malloc() is unable to allocate memory, it sets im_error() 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, using im_free().

int im_free( void *mem )

Three macros 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(), operates in the same way, 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 nelem, 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.


next up previous contents
Next: 2.3 Output to an Up: 2. Programming WIO operations Previous: 2.1 Input from an   Contents
John Cupitt 2004-11-02