Additional Topics > External Development Guide > IDLInternals - Variables > Getting Dynamic Memory

# Getting Dynamic Memory

Many programs need to get dynamic memory for some temporary calculation. In the C language, the functions malloc() and free() are used for this purpose, while other languages have their own facilities. IDL provides its own memory allocation routines (see Dynamic Memory). Use of such facilities within the IDL interpreter and the system routines can lead to the loss of usable dynamic memory. The following code fragment demonstrates how this can happen.

For example, assume that there is a need for 100 IDL_LONG integers:

char *c;

c = (char *) IDL_MemAlloc((unsigned) (sizeof(IDL_LONG) * 100)

(char *) 0, IDL_MSG_RET);

.

.

.

if (some_error_condition) IDL_Message(…, IDL_MSG LONGJMP,…);

.

.

.

IDL_MemFree((void *) c, (char *) 0, IDL_MSG_RET);

In the normal case, the allocated memory is released exactly as it should be. However, if an error causes the IDL_Message() function to be called, execution will return directly to the interpreter and this code will never have a chance to clean up. The dynamic memory allocated will therefore leak, and although it will continue to occupy space in the IDL processes, will not be used again.

## The IDL_GetScratch() Function

To solve this problem, use a temporary variable to obtain dynamic memory. Then, if an error should cause execution to return to the interpreter, the interpreter will

reclaim the temporary variable and no dynamic memory will be lost. This frequently- needed operation is provided by the IDL_GetScratch() function:

char *IDL_GetScratch(IDL_VPTR *p, IDL_MEMINT n_elts, IDL_MEMINT elt_size)

where:

### p

The address of an IDL_VPTR that should be set to the address of the temporary variable allocated.

### n_elts

The number of elements for which memory should be allocated.

### elt_size

The length of each element, in bytes.

Once the need for the temporary memory has passed, it should be returned using the IDL_Deltmp() function. Using these functions, the above example becomes:

char *c;

IDL_VPTR v;

c = IDL_GetScratch(&v, 100L, (IDL_LONG) sizeof(IDL_LONG));

.

.

.

if (some error condition) IDL_Message(...,MSG LONGJMP,...);

.

.

. IDL_Deltmp(v);

Using the IDL_GetScratch() and IDL_Deltmp() functions is similar to using IDLMemAlloc() directly. In fact, IDL uses IDL_MemAlloc() and IDL_MemFree() internally to implement array variables. The important difference is that dynamic memory doesn’t leak when error conditions occur.

To avoid losing dynamic memory, always use the IDL_GetScratch() function in preference to other ways of allocating dynamic memory, and use IDL_Deltmp() to return it.