[Fortran] nullify pointers before checking associated status
In Fortran the status of a pointer can be: undefined, not associated or associated. The first is the status upon creating the pointer, which implies that calling associated on it is undefined behavior.
Some examples are:
real, pointer :: p
if (.not.associated(p)) write(*, *) 'This is undefined behavior'
The correct solution is
real, pointer :: p
nullify(p)
if (.not.associated(p)) write(*, *) 'This is correct'
When working with derived types
type t_special
real, pointer :: p
end type t_special
type(t_special) a
if (.not.associated(a%p)) write(*, *) 'This is undefined behavior'
The correct solution is
type t_special
real, pointer :: p => null()
end type t_special
type(t_special) a
if (.not.associated(a%p)) write(*, *) 'This is correct'
A pointer can be nullified using nullify(p) and p => null(). Since the latter can be used everywhere, and not just in the definition of a type, it would be nice to normalize its usage.
Once again, thank you so much for your contribution, @RRiva! :-)
As per your comment here https://github.com/codee-com/open-catalog/issues/38#issuecomment-2373809507, we will prioritize this check and plan to add it to the catalog in the near future!
Hi @RRiva!
We've recently added a new check to the Open Catalog that addresses the issues of using uninitialized variables:
This check discusses how to prevent undefined behavior caused by different types of uninitialized variables, including, but not limited to, Fortran pointers. Motivated by these scenarios you shared with us, we discuss nullification as a way to increase their safety.
We hope you find this new check helpful! We'll keep the issue closed, but if you have any further suggestions or would like to continue the discussion, feel free to comment here or open a new issue.
Nice work @alvrogd 🙂