PDA

View Full Version : Dangling pointers


R. T. (Fortran Man)
12-08-2003, 05:37 PM
I hear that dangling pointer are bad. Just what is a dangling pointer?

Lahey Support
12-08-2003, 05:46 PM
A dangling pointer occurs when the thing that a pointer is pointing at becomes undefined. Except in an extremely limited set of circumstances, an undefined pointer must not be referred to, any reference can cause unpredictable results. In this context. "unpredictable" can range from the program apparently executing successfully, to executing but getting wrong answers, to crashing. Dangling pointers can be extremely difficult to detect, and in fact, the Fortran standard explicitly states that those implementing the Fortran standard have no obligation to detect a pointer in a dangling condition.

The only time an undefined pointer can be referred to is when inquiring about the characteristics of the data type that the pointer represents. For example it is permitted to use an undefined variable in the BIT_SIZE function.

All pointers are initially undefined, and referring to them before their status has been defined is taboo. The best way to define the status of a pointer is to nullify it at the time it is declared. For example:


real, pointer :: a(:)
real, pointer :: b(:) => null()


The status of "a" is undefined, and it must be defined before it can be referred to, or tested for association status. The status of "b" is defined, and "b" has a "disassociated" status.

One thing that might cause a dangling pointer is to point to an allocated variable, and then to deallocate the allocatable variable without nullifying or reassigning the pointer. The pointer variable then has an undefined status, i.e. it is left "dangling".

Another thing that might cause problems is to assign a pointer dummy variable to a local variable in a subprogram. On exit from the subprogram, the local variable might become undefined, and leave the pointer dangling.