open-catalog icon indicating copy to clipboard operation
open-catalog copied to clipboard

[Fortran] nullify pointers before checking associated status

Open RRiva opened this issue 1 year ago • 1 comments

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.

RRiva avatar Sep 27 '24 08:09 RRiva

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!

inaki-amatria avatar Oct 02 '24 09:10 inaki-amatria

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.

alvrogd avatar Dec 19 '24 12:12 alvrogd

Nice work @alvrogd 🙂

RRiva avatar Dec 20 '24 14:12 RRiva