For Programmers: Free Programming Magazines  


Home > Archive > Fortran > June 2004 > Dynamic memory, allocs and pointers









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Dynamic memory, allocs and pointers
Anthony

2004-06-29, 3:57 am

Hi,

In example the routine 'pointers' is used for wrapping
F90's ALLOCATE with some proper error handling included.
file test.f:
program test
use pointers_mod
real, allocatable, dimension(:) :: a ! is this the
right declaration ???
n = 10
call pointers(a,n)
a = (/(i,i=1,n)/)
write(*,*) ' Memory used so far ',memory_used
end program test

file pointers.f:
module pointers_mod
integer :: memory_used=0
contains
subroutine pointers(a,n)
integer :: n, error
real, dimension(:), allocatable :: a
allocate(a(n), stat=error)
memory_used= memory_used+ n
if (error /=0) stop 'Memory problem'
end subroutine pointers
end module pointers_mod

In Visual Fortan (MS Dev Studio) this works nice, but I have
doubt about the declaration of array 'a' in the main
program.

Or must this better be replaced by declaration

real, pointer, dimension(:) :: a

from the idea that routine 'pointers' returns a pointer to
the just allocated array. Something you have in C programs.
I know that pointers in F90 work more like aliases, so are
different the 'real pointers' in C.

At the other hand, the example above works for both
declarations, thus it gives the expected result.

Some help would be nice.

Thanks.
Anthony.



Jan Vorbrüggen

2004-06-29, 3:57 am

> Or must this better be replaced by declaration
>
> real, pointer, dimension(:) :: a
>
> from the idea that routine 'pointers' returns a pointer to
> the just allocated array.


The answer is: it depends on the compiler you have. Strict F95-conforming
compilers do not allow a dummy argument to be ALLOCATABLE, and you have to
use the POINTER method. But that is a crutch, and it has some problems in
various situations that cannot be solved (e.g., they lead to memory leaks
if you use an array-valued function in an expression). However, there is an
"extension" to F95 called the "ALLOCATABLE TR". Almost all compilers on the
market now support it, and you can use your code as is. Basically, if your
compiler compiles it, you're OK (modulo compiler bugs, of which there were
many in support of this feature initially). But be aware that you might want
to run this using a compiler that doesn't (yet) support the TR, and then you
would need to change back to the POINTER variant. Whether that is relevant
to your application, only you can decide.

Jan
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com