14

I am writing a new code in Fortran and hesitating between using allocatable arrays or pointer arrays. I read somewhere that allocatable arrays have significant advantages over pointer arrays:

1) More efficient because they are always contiguous in memory

2) No memory leaks are possible

Can someone confirm this? Which one would you advise to use? What are the results in term of execution speed of the code between these two alternatives?

2
  • Why can't you memory leak? Don't you have to DEALLOCATE any array you made with allocatable? Commented Feb 19, 2010 at 23:07
  • @Carl - you mean with "allocate" ... Commented Feb 19, 2010 at 23:46

1 Answer 1

22

Allocatable arrays can result in more efficient code because the arrays will be contiguous. Particularly if the array is passed to a subroutine, being contiguous can prevent the need for the compiler creating a temporary copy.

For local variables in subroutines (without the SAVE attribute) (for Fortran 95 and higher), allocatable arrays are automatically deallocated upon exit from the subroutine, avoiding a memory leak. Memory leaks aren't possible with allocatables, except in the sense of the programmer not deallocating an array that is no longer need.

With pointers, you can reassign a pointer, leaving some memory inaccessible and lost -- one form of a leak. If an allocatable will do the job, I recommend using that method instead of a pointer.

Some reasons to use pointers: taking a section of an array, or creating a data structure such as a linked list. For the purpose of creating an array of size determined at run time, I'd use an allocatable.

Sign up to request clarification or add additional context in comments.

1 Comment

update: with Fortran 2008 it is possible to create linked lists using allocatable variables instead of pointers. See item 5.3 of ftp.nag.co.uk/sc22wg5/N1701-N1750/N1729.pdf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.