I'm using gfortran -std=f2008. I have a function that returns a derived type which contains an allocatable array. The function calls allocate() before it returns. It seems like the array is being automatically deallocated some time after the function that allocated the array has returned, and my program segfaults.
When does automatic deallocation occur? Should I be coding this in a different way?
Purpose. The DEALLOCATE statement dynamically deallocates allocatable objects and pointer targets. A specified pointer becomes disassociated, while any other pointers associated with the target become undefined.
You are responsible for deallocating the variable before doing it or else memory leaks will happen. As a final note, trying to deallocate a variable that is not allocated throws an error. You can check if an allocatable variable is allocated with the intrinsic function allocated . Save this answer.
A universal answer: allocatable arrays are automatically deallocated when going out of scope. Function results are automatically deallocated after the result is "used" in the outer scope. Allocatable components are deallocated, when the parent derived type variable is going out of scope, or when it is deallocated.
Only pointers
, that pointed to the function results are undefined after the deallocation and shall not be used. If you do that, it could cause the problems you describe.
Also, when an array is automatically reallocated on assignment, the pointers to it become undefined (but may not change, actually).
In other words, problems you describe shouldn't occur when the allocatables are used correctly.
Another general advice : most of the time, it is much safer to use subroutines instead of functions for returning complicated results like arrays, pointers, derived types with allocatable inside...
Additional question : do you use your function within an expression ? If not then it should be a subroutine. Fortran functions have only interest if used within calculation expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With