# Dangling References

If Automatic Garbage Collection is turned off for a heap variable and the variable is destroyed using PTR_FREE or OBJ_DESTROY, any remaining pointer variables or object references that still refer to it are "dangling references." Unlike lower level languages such as C, dereferencing a dangling reference will not crash or corrupt your IDL session. It will, however, fail with an error message. For example:

;Create a new heap variable.

A = PTR_NEW(23)

;Print A and the value of the heap variable A points to.

PRINT, A, *A

IDL prints:

<PtrHeapVar13> 23

For example:

;Destroy the heap variable.

PTR_FREE, A

;Try to print again.

PRINT, A, *A

IDL prints:

% Invalid pointer: A.

% Execution halted at: $MAIN$

There are several possible approaches to avoiding such errors. The best option is to structure your code such that dangling references do not occur. You can, however, verify the validity of pointers or object references before using them (via the PTR_VALID or OBJ_VALID functions) or use the CATCH mechanism to recover from the effect of such a dereference.