Reputation: 79
I have a code similar to this:
module mod
implicit none
real, pointer :: p1=>null(), p2=>null()
end module mod
program target_lifetime
use mod
implicit none
real, target :: t(2)
p1 => t(1)
p2 => t(2)
nullify( p1, p2 )
end program target_lifetime
When I compile this code with
gfortran -Wall target_lifetime.f90
I obtain
target_lifetime.f90:14:4:
14 | p1 => t(1)
| 1
Warning: Pointer at (1) in pointer assignment might outlive the pointer target [-Wtarget-lifetime]
target_lifetime.f90:15:4:
15 | p2 => t(2)
| 1
Warning: Pointer at (1) in pointer assignment might outlive the pointer target [-Wtarget-lifetime]
What is the correct way to code this in order to get rid of the warning?
Upvotes: 0
Views: 192
Reputation: 900
Vladimir is likely correct that this a side-effect of the implicit save of t1
and t2
. Fortunately, the warning is generated from only one place within the gfortran source code. This means that you can easily suppress the warnings with this patch.
diff --git a/gcc/fortran/expr.cc b/gcc/fortran/expr.cc
index 290ddf360c8..543d4e24286 100644
--- a/gcc/fortran/expr.cc
+++ b/gcc/fortran/expr.cc
@@ -25,6 +25,7 @@ along with GCC; see the file COPYING3. If not see
#include "gfortran.h"
#include "arith.h"
#include "match.h"
+#include "parse.h"
#include "target-memory.h" /* for gfc_convert_boz */
#include "constructor.h"
#include "tree.h"
@@ -4523,7 +4524,10 @@ gfc_check_pointer_assign (gfc_expr *lvalue, gfc_expr *rvalue,
break;
}
- if (warn)
+ if (warn
+ && (gfc_current_state () != COMP_PROGRAM)
+ && (!(gfc_current_state () == COMP_NONE
+ && !gfc_state_stack->previous)))
gfc_warning (OPT_Wtarget_lifetime,
"Pointer at %L in pointer assignment might outlive the "
"pointer target", &lvalue->where);
Upvotes: 0
Reputation: 60018
The warning here is clearly bogus because of the lifetime of the main program variable is until the end of the program and the t
array is implicitly save
.
There is not much you can do. You can open a bug with GCC and ask whether it is possible to change the behaviour here.
I can see that it could be triggered by internally implementing the __MAIN
(or some other name) procedure as a subroutine (actually a funciton in C or GIMPLE) and then treating the variables as local variables in some checks. But then the standard still says that the variables in the main program are save
implicitly.
Upvotes: 2