Clash between copy assignment and constructor in Fortran - fortran

I have the following code which is producing a segmentation fault. It does complain that
forrtl: severe (408): fort: (7): Attempt to use pointer TT when it is not associated with a target
Now I am pretty sure what the reason is, namely, it is trying to access my copy assignment routine, while I am just trying to initialise the object.
By commenting out generic :: assignment(=) => copy it works fine!
I am compiling the code as follows : (IFORT version 19.0.3)
ifort -O0 -debug full -check all -traceback -g -C -CB -CU -CA -fpp filaname.f90
and running by ./a.out
module md
implicit none
type T_TEST
integer :: ii
contains
procedure, pass(this) :: COPY
generic :: assignment(=) => copy
end type
interface t_test
module procedure init
end interface t_test
type(t_test) , allocatable :: tt
contains
function init( size )
integer, intent(in) :: size
type(t_test) , allocatable :: init
allocate( init )
init% ii = size
end function
subroutine copy(this, old )
class(t_test), intent(out) ::this
type(t_test), intent(in) :: old
this% ii = old% ii
end subroutine
end module md
program t_Testprogram
use md
implicit none
tt = t_test( 100 )
end program t_Testprogram

The reason is that the overloaded assignment copy does not support allocatable left hand sides. So when the value of this is used in this% ii = old% ii , it actually does not exist and a null pointer is used. But I do agree the Intel's error message is confusing or even incorrect.
The automatic left hand side (re-)allocation only applies to intrisic assignments, not to user defined ones. In user-defined ones you must program yourself the exact behaviour. And you did not specify anything for not-allocated left hand sides.
This works for me:
type T_TEST
integer :: ii
end type
interface assignment(=)
procedure copy
end interface
subroutine copy(this, old )
class(t_test), allocatable, intent(out) ::this
type(t_test), intent(in) :: old
if (.not.allocated(this)) allocate(this)
this% ii = old% ii
end subroutine
Or you can just allocate the object first (that is what I would do here because gfortran seems to not like generic resolution based on the allocatable attribute - a F08 feature).
allocate(tt)
tt = t_test( 100 )
It seems that you are thinking that just because the constructor has its result variable "marked" allocatable, it will allocate the left hand side of the assignment for you. It is not so. The only thing it does it that it allocates its own result as a temporary variable. This result is then assigned in tt = t_test() and then deallocated automatically.
Remember, the result variable is not the same as the left hand side of the assignment. The result can be used in an expression of many different types, not just in an assignment. It can be passed to a subroutine, it can be used in an arithmetic expression, it can be printed...
Your constructor can be just
function init( size )
integer, intent(in) :: size
type(t_test) :: init
init% ii = size
end function
and the result will be exactly the same. There is no reason to make it allocatable, it just complicates it, but does not change the result in the slightest.
Maybe what you are trying to follow some C++ RAII principles, but remember, C++ is simply not Fortran.

Related

How to correctly read a C-string into a Fortran string of unspecified length?

The following function is supposed to convert a C string into a Fortran string and works fine in Release builds, but not in Debug:
! Helper function to generate a Fortran string from a C char pointer
function get_string(c_pointer) result(f_string)
use, intrinsic :: iso_c_binding
implicit none
type(c_ptr), intent(in) :: c_pointer
character(len=:), allocatable :: f_string
integer(c_size_t) :: l_str
character(len=:), pointer :: f_ptr
interface
function c_strlen(str_ptr) bind ( C, name = "strlen" ) result(len)
use, intrinsic :: iso_c_binding
type(c_ptr), value :: str_ptr
integer(kind=c_size_t) :: len
end function c_strlen
end interface
l_str = c_strlen(c_pointer)
call c_f_pointer(c_pointer, f_ptr)
f_string = f_ptr(1:l_str)
end function get_string
However, it seems that c_f_pointer does not tell the Fortran pointer-to-string, f_ptr, the length of the string it is pointing to. In Debug builds, where bounds-checking is active, this results in
Fortran runtime error: Substring out of bounds: upper bound (35) of 'f_ptr' exceeds string length (0)
I'm using gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 and set the standard to 2008.
My question: Is there any way to tell the f_ptr its length without changing the declaration or am I doing something fundamentally the wrong way here?
It seems to run correctly if I specify the shape, but for that f_ptr needs to be an array:
character(len=:), allocatable :: f_string
character(len=1), dimension(:), pointer :: f_ptr
...
call c_f_pointer(c_pointer, f_ptr, [l_str])
However, I cannot find a way to transform that string of rank 1 to the character(len=:), allocatable :: f_string, which apparently has rank 0.
My second question: Is there any way to transfer the f_ptr data into the f_string in this example?
You cannot use c_f_pointer to set the length of the Fortran character pointer (F2018, 18.2.3.3):
FPTR shall be a pointer, shall not have a deferred type parameter [...]
A deferred-length character scalar (or array) therefore cannot be used (the length is a type parameter).
You can indeed use a deferred-shape character array as fptr and then use any number of techniques to copy the elements of that array to the scalar (which is rank-0 as noted).
For example, with substring assignment (after explicitly allocating the deferred-length scalar):
allocate (character(l_str) :: f_string)
do i=1,l_str
f_string(i:i)=fptr(i)
end
Or consider whether you can simply use the character array instead of making a copy to a scalar.

How can I introduce an allocatable array which allocate in subroutine [duplicate]

UPDATE: My modified code looks like this:
program run_module_test
use module_test
implicit none
TYPE(newXYZ), allocatable, intent(inout) :: xyzArray(:)
call update(xyzArray)
write(6,*)'xyzArray',xyzArray
end program run_module_test
module module_test
implicit none
TYPE :: newXYZ
real(4) :: x, u
real(4) :: y, v
real(4) :: z, w
real(4),dimension(3) :: uvw
END TYPE
integer(4) :: shape = 3
contains
subroutine update(xyzArray)
integer(4) :: i
TYPE(newXYZ), allocatable, intent(inout) :: xyzArray(:)
allocate( xyzArray(shape) )
do i = 1, shape
xyzArray(i)%x = 0
xyzArray(i)%y = 0
xyzArray(i)%z = 0
xyzArray(i)%u = 0
xyzArray(i)%v = 0
xyzArray(i)%w = 0
xyzArray(i)%uvw = (/0,0,0/)
end do
return
end subroutine update
end module module_test
When they are compiled, they generate a similar error:
TYPE(newXYZ), allocatable, intent(inout) :: xyzArray(:)
1
Error: ALLOCATABLE attribute conflicts with DUMMY attribute at (1)
When I eliminate the argument in update() subroutine, I receive a contradictory error:
TYPE(newXYZ), allocatable, intent(inout) :: xyzArray(:)
1
Error: Symbol at (1) is not a DUMMY variable
Have I eliminated the sources of error pointed out in the helpful suggestions? Could this be a compiler related error (using mpi90)?
~~~First Edit~~~
I have a subroutine whose input argument is an array of user defined type XYZ. I wish to deallocate xyzArray and allocate/modify it to a different size in the body of the subroutine. I attempted the method suggested by changing array dimensions in fortran, but when I do the following:
subroutine update(xyzArray, ...)
...
TYPE (XYZ), allocatable :: xyzArray(:)
I receive an error message:
Error: ALLOCATABLE attribute conflicts with DUMMY attribute at (1)
When I try:
subroutine update(xyzArray, ...)
...
deallocate( xyzArray(myshape) )
allocate( xyzArray(newshape) )
I receive error messages:
Error: Expression in DEALLOCATE statement at (1) must be ALLOCATABLE or a POINTER
Error: Expression in ALLOCATE statement at (1) must be ALLOCATABLE or a POINTER
What do I need to do to change the size of the array in the subroutine?
To do this:
The dummy argument must be allocatable. Allocatable dummy arguments require a compiler that implements the relevant part of the Fortran 2003 standard (or a Fortran 95 compiler that implements the so called "allocatable" TR).
An explicit interface to the procedure is required (the procedure must be a module procedure, an internal procedure or have an interface block in the calling scope).
The dummy argument must not be intent(in). If you are not using the allocation status or other aspects of the value of the dummy argument at all in the subroutine then intent(out) may be appropriate (if allocated beforehand the dummy argument will be automatically deallocated when the procedure is called), otherwise intent(inout) or no intent.
(Your second block of example code has a syntax error with the deallocate statement - you should simply specify the xyzArray variable, leave off the (myshape) shape specification))
For example, in a module:
subroutine update(xyzArray)
type(xyz), allocatable, intent(inout) :: xyzArray(:)
...
if (allocated(xyzArray)) deallocate(xyzArray)
allocate(xyzArray(newshape))
...
If you are sure, you want to deallocate the array in your subroutine, you can declare the dummy argument being intent(out), so that it is deallocated automatically when the subroutine is entered:
module whatever
implicit none
type :: xyz
:
end type xyz
contains
subroutine update(xyzArray)
type(xyz), allocatable, intent(out) :: xyzArray(:)
:
allocate(xyzArray(someshape))
:
end subroutine update
end module whatever
As already noted by IanH, the process must have an explicit interface (e.g. being enclosed in a module) and in the caller program you must declare the actual argument allocatable:
program test
use whatever
implicit none
type(xyz), allocatable :: array(:)
:
call update(array)
:
end program test

How to use allocatable arrays in Fortran subroutines?

Let me just preface this by saying that I am very new to Fortran but familiar with Python. My research project however requires me to use some pre-written Fortran code, which at this moment wont compile on my pc. I am trying to understand why.
The actual code I am trying to compile is very long and probably not very illuminating, but I think I have managed to come up with a minimal example of where I think the issue is. Let's say I have a very simple module and subroutine as follows,
module arraycheck
implicit none
real*8, allocatable, dimension(:) :: x
contains
subroutine fillx
real*8, allocatable, dimension(:) :: x
allocate(x(5))
x(1) = 1
x(2) = 2
x(3) = 3
x(4) = 4
x(5) = 5
print*, x
end subroutine fillx
end module arraycheck
which I expect to simply create an array x, which when the subroutine fillx is called fills the array with the integers 1 to 5. My actual source contains something conceptually similar to this. Now I also have a main program as follows,
program main
use arraycheck
print*, x
call fillx
print*,x
end
My idea here would be that on the first print statement the variable x is still unallocated, so print returns nothing, and then on the second print statement x has been filled, so it should return the filled array.
However on both print statements nothing is returned. Now in my original source code something similar happens, which causes runtime to throw an error that an unallocated array was passed somewhere as an actual argument, which should have been allocated. It seems like the exact same thing happens as in my small example here.
So my question is, is the behaviour that I observe in my example here expected? And if it is, how can I alter the code to make it work in the way that I would want it to? If I know this I might better understand why the actual source doesn't work.
Just in case it is relevant, I am using gfortran on ubuntu.
Thanks!
You have too different xs. They do not have anything in common. One a module array and one array local to the subroutine. When you allocate the local array in the subroutine, it does not do anything to the other array in the module.
Also, you cannot print array that is not allocated. That is not standard conforming (undefined behaviour). Anything can happen. You should definitely enable all compiler checks when diagnosing problems. The compiler should complain about your code with those checks.
Remove the local array declaration and avoid referencing unallocated variables. Module procedures have access to module variables through host association.
module arraycheck
implicit none
real*8, allocatable, dimension(:) :: x
contains
subroutine fillx
allocate(x(5))
x(1) = 1
x(2) = 2
x(3) = 3
x(4) = 4
x(5) = 5
print*, x
end subroutine fillx
end module arraycheck
program main
use arraycheck
call fillx
print*,x
end
Also, real*8 is not standard Fortran, it is a non-standard extension. Fortran 90 and later uses the kind system instead.
Here are some other things which might be helpful - shown in UPPERCASE.
module arraycheck
USE ISO_C_BINDING, ONLY : C_Int32_t, C_DOUBLE
implicit none
PRIVATE
real(KIND=C_DOUBLE), allocatable, dimension(:), PUBLIC :: x
PUBLIC Creation_X, Destruction_X, FillX
contains
subroutine Creation_X(n)
USE ISO_C_BINDING, ONLY : C_Int32_t
IMPLICIT NONE
INTEGER(KIND=C_Int32_t), INTENT(IN) :: n
allocate(x(n))
RETURN
end subroutine Creation_X
subroutine Destruction_X
USE ISO_C_BINDING, ONLY : C_Int32_t
IMPLICIT NONE
IF(ALLOCATED(X)) DEALLOCATE(X)
RETURN
end subroutine Destruction_X
subroutine fillx
USE ISO_C_BINDING, ONLY : C_Int32_t
IMPLICIT NONE
INTEGER(KIND=C_Int32_t) :: N
DO I= 1, SIZE(x)
x(I) = I
ENDDO
RETURN
end subroutine fillx
end module arraycheck
program main
use arraycheck
CALL Creation_X(5)
call fillx
print*,x
CALL Destruction_X
end

Could declaration of pointers to derived types be undefined?

I have a small code declaring a pointer to array of derived type which has a field that is an allocatable array of another derived type having a real variable as a field.
Using gnu fortran (8.2) I obtain different results for each location in the array or as a vector.
Using intel fortran (2019.4) compiler succeeded.
program test
implicit none
integer, parameter :: length = 2
real(8), dimension(length) :: a, b
integer :: i
type point
real(8) :: x
end type point
type stored
type(point), dimension(:), allocatable :: np
end type stored
type(stored), dimension(:), pointer :: std=>null()
allocate(std(1))
allocate(std(1)%np(length))
std(1)%np(1)%x = 0.3d0
std(1)%np(2)%x = 0.3555d0
do i = 1, length
write(*, "('std(1)%np(',i1,')%x = ',1e22.14)") i, std(1)%np(i)%x
end do
do i = 1, length
write(*, "('std(1)%np(1:',i1,') = ',2e22.14)") i, std(1)%np(1:i)%x
end do
a = std(1)%np(1:2)%x
b = [std(1)%np(1)%x, std(1)%np(2)%x]
if (norm2(a - b) .gt. 1d-3) then
write(*,*) 'failure'
else
write(*, *) 'success'
end if
end program test
the code terminates successfully, but using gfortran one obtains 'failure' on screen and inconsistent prints above and using Intel compiler one obtains 'success' on screen and consistent prints above.
It's not clear to me what your question is, unless it's the title. If so, no, pointers to derived types are fine. Your program correctly allocates std as an extent-1 array and then allocates std(1)%np(2). It then assigns to the x subcomponents of both np elements. Looks fine to me.
There are several things that could potentially cause "failure" - you should run the gfortran code in the debugger to see what is going wrong.
The problem presented in the code above was resolved in the following [link] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91077

fortran "array of arrays" and "pack" issues

I seem to have hit a wall while coding these past few days. from what i can gather, it is possible to make arrays of arrays in fortran ala Fortran array of variable size arrays
type par
.... !data
integer :: location
end type par
type locations
....! data
type (par), allocatable, dimension(:) :: pars
end type locations
type (par), allocatable, dimension(:) :: all_pars
type (locations), allocatable, dimension(:) :: all_loc
.... !read numpars, numlocs from file etc
allocate(all_pars(numpars))
allocate(all_locs(numlocs))
!initialize all_pars
do n = 1:numpars
....
all_pars(n)%location = some_location
enddo
!get particles in each location
do n = 1:numlocs
allocate(all_locs(n)%pars(count(all_pars(:)%location .ne. n)))
all_locs(n)%pars = pack(all_pars, (all_pars(:)%location .ne. n)) !ERROR: An assignment of different structure types is invalid.
enddo
the compiler does not complain with my equivalent lines of code for the stack overflow example above, but it indeed does have an issue when i attempt to use that array to store the result of a pack function call. i suspect that it may be the case that the allocate function is not behaving as expected, but since the code does not compile, i cannot debug it....
the squirrely idea for pack usage comes from http://flibs.sourceforge.net/fortran_aspects.html , about halfway down the page.
I am running on a linux system, with ifort 12.1.3.293
any help is much appreciated
This may be an extended comment rather than an answer ...
to get it to compile I modified your posted code to;
program main
implicit none
integer :: numpars, numlocs, n
type par
!data
integer :: location
end type par
type locations
! data
type (par), allocatable, dimension(:) :: pars
end type locations
type (par), allocatable, dimension(:) :: all_pars
type (locations), allocatable, dimension(:) :: all_locs
!read numpars, numlocs from file etc
numpars = 10
numlocs = 4
allocate(all_pars(numpars))
allocate(all_locs(numlocs))
!initialize all_pars
all_pars(1:numpars:4)%location = 1
all_pars(2:numpars:4)%location = 2
all_pars(3:numpars:4)%location = 3
all_pars(4:numpars:4)%location = 4
!get particles in each location
do n = 1,numlocs
! allocate(all_locs(n)%pars(count(all_pars(:)%location .ne. n)))
all_locs(n)%pars = pack(all_pars, (all_pars(:)%location .ne. n))
enddo
end program
and it compiles without a hitch on my Mac with Intel Fortran 13.something. Of course, since you've only posted a syntactically-slightly-incorrect part of your code I can't be sure that this tells you very much.
Since you don't show that your code uses implicit none your error might be down to the difference between all_loc and all_locs or some other similar issue.
Note, in passing, that with Fortran allocatable arrays you don't need to allocate all_locs(n)%pars prior to setting its value with the call to pack, the compiler will take care of that for you. This, though, is not the source of your error.