1
votes

I try to deallocate a class(*) pointer which points to an object of another type.

I know the difference between declared type and dynamic type. I should not be able to access any variable in the object with a class(*) pointer. So I was expecting an error when deallocating the object with class(*) pointer. However it works fine. Valgrind also shows no memory leak.

I am curious why. Does this mean "deallocate" implicitly detect the dynamic type? Any explanation would be appreciated.

class(*),     pointer :: ptr => NULL()
class(point), pointer :: ptr_pnt => NULL() ! point is a derived data type

allocate( ptr_pnt )

... ! set the data in ptr_pnt

ptr => ptr_pnt
deallocate( ptr )
nullify( ptr_pnt )
1

1 Answers

2
votes

Yes - deallocation considers the dynamic type. The code fragment is standard conforming.

At runtime the internals of the program know the dynamic type of the object that the polymorphic pointer refers to - a polymorphic object may be implemented by a descriptor that tracks both the data of the object and the type and type parameters of the object. This knowledge is how the program can execute constructs such as SELECT TYPE.

When deallocating an object through a pointer, there are requirements that the object being deallocated be something that was previously allocated through a pointer (but it doesn't have to be the same pointer - note also that the Fortran runtime has to have the ability to detect violations of this requirement) and that the pointer that refers to the thing being deallocated has to refer to the whole of the thing (i.e. if you have an object of extended type you cannot deallocate through a non-polymorphic pointer to a parent component of the object). Your code meets both of these requirements.