alexis
alexis

Reputation: 430

Deallocate pointer target from a pointer alias in Fortran 90

the code

program asd

real,pointer        :: a,b,c

allocate(a)
a=2.0
b=>a
c=>a
deallocate(b) !
print *, associated(c,target=a) ! T

end program

return T with intel compiler. I conclude that "b" is not a full alias of "a", since I can not deallocate "a" taking "b". So my question is: if I construct a pointer with

function ptr
  real,pointer   :: var,ptr
  allocate(var)
  ptr=>var
end function

It is possible to deallocate var after to call this function?

Thank a lot-

Upvotes: 3

Views: 4076

Answers (1)

tpg2114
tpg2114

Reputation: 15100

The standard says (section 6.3.3.2):

... Deallocating a pointer target causes the pointer association status of any other pointer that is associated with the target or a portion of the target to become undefined.

Further on, in section 16.4.2.1, it says:

A pointer may have a pointer association status of associated, disassociated, or undefined.

and in note 16.3 it points out that:

A pointer from a module program unit may be accessible in a subprogram via use association. Such pointers have a lifetime that is greater than targets that are declared in the subprogram, unless such targets are saved. Therefore, if such a pointer is associated with a local target, there is the possibility that when a procedure defined by the subprogram completes execution, the target will cease to exist, leaving the pointer “dangling”. This standard considers such pointers to have an undefined association status. They are neither associated nor disassociated. They shall not be used again in the program until their status has been reestablished. There is no requirement on a processor to be able to detect when a pointer target ceases to exist.

All of that is to say that the result of .TRUE. from Intel you are getting is compiler-specific because c has an undefined association status, which compilers can report any way they want. If you tried to access a through c, you would get a memory error (or even if it works, it is undefined and not a guarantee).

Likewise, your example function is just as dangerous because there is no guarantee that var will exist when the function returns, meaning the ptr function result is again undefined. So again, if you tried to access var through the result of ptr, you would again get a memory error.

If you want your function to work, it would need to look like:

function ptr
  real, pointer, save :: var
  real,pointer   :: ptr
  allocate(var)
  ptr=>var
end function

Of course, this begs the ultimate question -- why ALLOCATE pointers? It's much safer to use ALLOCATABLE for the target and give it the TARGET attribute.

Upvotes: 9

Related Questions