Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fortran] nullify pointers before checking associated status #39

Closed
RRiva opened this issue Sep 27, 2024 · 3 comments · Fixed by #56
Closed

[Fortran] nullify pointers before checking associated status #39

RRiva opened this issue Sep 27, 2024 · 3 comments · Fixed by #56
Assignees

Comments

@RRiva
Copy link

RRiva commented Sep 27, 2024

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.

@inaki-amatria
Copy link
Contributor

Once again, thank you so much for your contribution, @RRiva! :-)

As per your comment here #38 (comment), we will prioritize this check and plan to add it to the catalog in the near future!

@alvrogd
Copy link
Collaborator

alvrogd commented Dec 19, 2024

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.

@RRiva
Copy link
Author

RRiva commented Dec 20, 2024

Nice work @alvrogd 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants