2
votes

I am new to Fortran. My question is why do we need allocatable arrays in Fortran? I know one benefits is you do not need to know the dimensions beforehand. But is there also performance reasons?

For example, after the array is used is no going to be reused in the future, we will deallocate the array. Does this deallocate help free up more memory comparing to not using allocatable arrays, namely the regular arrays?

2
What makes you think that they are needed in Fortran? Most language features are for convenience, not necessity. - John Coleman
@JohnColeman I actually didn't think too much when I wrote down the word "needed." My primary question is actually do deallocating actually help free up memory space so future data can be stored in these locations. - Kun
I was just being pedantic. Its been years since I've done anything in Fortran, so I can't speak to that, but if my experience with C is any guide (where it is common to malloc an array into existence), the flexibility of being able to determine the size dynamically at run time is the main motivation rather than the ability to free up the memory when done. The latter is important mostly as an enabling technology since it makes it possible to implement the former without creating memory leaks. - John Coleman
@JohnColeman : In my opinion, his question makes a lot of sense even though this may not be good platform to ask this basic question. I am afraid that elite community doesn't want to understand beginners' problems many times and this fuss about "needed" is a very good example of that. - Peaceful

2 Answers

3
votes

Allocatable arrays serve two purposes:

  1. You don't have to know the size of the array at compile time.
  2. You can minimise memory use.

Without allocatable arrays, you would have to select a static array size large enough to fit any possible size, which means that in most cases, you will use far more memory than necessary. And if you misjudged the possible size, you need to change the code and recompile.

Static arrays also consume their memory for the whole duration that they are in scope, so for arrays in the main program that would be the entire run time. Allocatable arrays can (and should be) deallocated if you don't need them any more in order to minimise memory use.

(Before allocatable arrays, you could use the EQUIVALENCE statement to make different variables and arrays use the same physical memory if you knew that you would never need them at the same time.)

2
votes

I know I shouldn't but ...

... we don't need no stinking allocatable arrays, we programmed in FORTRAN for 35 years without them ... just grab that 64K of RAM into a static array and we'll do our own memory management thank you very much ...

[Carried away in a strait-jacket ranting and foaming at the mouth.]