Heap Variable Leakage
Heap variables are not reference counted—that is, IDL does not keep track of how many references to a heap variable exist, or stop the last such reference from being destroyed—so it is possible to lose access to them and the memory they are using. For example:
;Create a new heap variable. A = PTR_NEW(23) ;Set the pointer A equal to the integer zero. The pointer to the ;heap variable created with the first command is lost. A = 0
Use the HEAP_VARIABLES keyword to the HELP procedure to view a list of heap variables currently in memory:
IDL prints:
In this case, the heap variable <PtrHeapVar14> exists and has a value of 23, but there is no way to reference the variable. There are two options: manually create a new pointer to the existing heap variable using the PTR_VALID function (see "PTR_VALID" (IDL Reference Guide)), or do manual "Garbage Collection" and use the HEAP_GC command to destroy all inaccessible heap variables.
Warning
Object reference heap variables are subject to the same problems as pointer heap variables. See "OBJ_VALID" (IDL Reference Guide) for more information.
The HEAP_GC procedure causes IDL to hunt for all unreferenced heap variables and destroy them. It is important to understand that this is a potentially computationally expensive operation, and should not be relied on by programmers as a way to avoid writing careful code. Rather, the intent is to provide programmers with a debugging aid when attempting to track down heap variable leakage. In conjunction with the VERBOSE keyword, HEAP_GC makes it possible to determine when variables have leaked, and it provides some hint as to their origin.
Warning
HEAP_GC uses a recursive algorithm to search for unreferenced heap variables. If HEAP_GC is used to manage certain data structures, such as large linked lists, a potentially large number of operations may be pushed onto the system stack. If so many operations are pushed that the stack runs out of room, IDL will crash.
General reference counting, the usual solution to such leaking, is too slow to be provided automatically by IDL, and careful programming can easily avoid this pitfall. Furthermore, implementing a reference counted data structure on top of IDL pointers is easy to do in those cases where it is useful, and such reference counting could take advantage of its domain specific knowledge to do the job much faster than the general case.
Another approach would be to write allocation and freeing routines—layered on top of the PTR_NEW and PTR_FREE routines—that keep track of all outstanding pointer allocations. Such routines might make use of pointers themselves to keep track of the allocated pointers. Such a facility could offer the ability to allocate pointers in named groups, and might provide a routine that frees all heap variables in a given group. Such an operation would be very efficient, and is easier than reference counting.