I am trying to loop over all arguments passed to a Fortran program, with the number of arguments varying. Thus I made the array of strings allocatable.
However once I to start said loop, I get a segfault, if any argument is given.
Is there any problem with having an allocatable string array?
CODE:
program read_args
implicit none
character(len=999), allocatable :: args(:)
integer, allocatable :: i, nargs
nargs=command_argument_count()
if ( nargs == 0 ) then
print*, 'err: no arguments or options'
stop
end if
allocate(args(1:nargs))
print*, nargs, size(args(:))
do i=1,nargs
call getarg(i,args(i))
args(i)=trim(adjustl(args(i)))
end do
end program
The number of arguments and array size is printed, once I try to read in the argument, I get a segfault.
Compiler, gfortran - gcc , v8.3.0 on debian 10
(To avoid XY-problems: the idea is to check for option flags in the argument list as well as to get all file names which should be processed)
Results:
$ ./a.out
err: no arguments or options
$ ./a.out arg1 arg2
2 2
<Segfault>
integer, allocatable :: i(:)). I had mixed allocatable (vectors, arrays) and scalar values on that line in the bigger program. Could you explain this further? Also I'll gladly accept this as an answer so the topic can be closed - independently of any explanations.iis never allocated in this program. You are probably aware that intrinsic assignment to an allocatable variable causes it to be allocated to the shape/length of the expression, but the use as a DO control variable isn't intrinsic assignment so that doesn't apply.rank=0could need allocation. Thank you for the explanation! For future readers: automatic allocation is Fortran 2003 standard. More details here.