Size of an unallocated array

@FLNewbiee, excellent design questions about Fortran. Here is my answer:

I think the best approach is to give a runtime error, since the operation is not defined.

Here is how you can ensure the compiler gives a runtime error with GFortran:

$ cat a.f90                      
integer, allocatable :: a(:), b(:)
allocate(a(10))
print *, size(a), size(b)
end
$ gfortran -fcheck=pointer  a.f90
$ ./a.out 
At line 3 of file a.f90
Fortran runtime error: Allocatable argument 'b' is not allocated

Error termination. Backtrace:
#0  0x1024b3c07
#1  0x1024b47a7
#2  0x1024b4be3
#3  0x1020c3d13
#4  0x1020c3d8f

(The stacktrace doesn’t work on my macOS, I haven’t had time to figure out how to fix it, I compiled GFortran using Spack.)

There are multiple approaches, it seems in this case size should just give a runtime error.

But I want to comment on the general approach: I recommend to think about Fortran in two modes: Debug build and Release build.

  • Debug build: build quickly, all checks enabled, so the Fortran code either will give a compiler error at compile time, or a runtime error. Ideally it can’t segfault or give any kind of undefined behavior.

  • Release build: can build slowly, but runs as quickly as possible. Checks are disabled, so it can segfault or produce bad numbers. If that happens, switch back to Debug mode and you’ll get a compile time or runtime error.

One can also think of a third mode: ReleaseSafe, which will run as fast as possible, but it will leave all checks on. That might be needed if you run the code as part of a webbrowser (let’s say), but for typical numerical codes you don’t need it.

Currently the compilers do not expose these modes easily, as a user you need to provide the appropriate options by hand. We are trying to fix that with fpm which has the two modes with some decent default options.

1 Like