1

I am curious about the sizeof Fortran derived type.

type structInt
  integer :: n
  double precision :: f
end type structInt

type(structInt) :: a

A sizeof( a ) gives (on my system) a result of 16 bytes, which is fine considering padding is added.

But if there is an allocatable array inside the derived type, then it jumps to 64 bytes.

type structArray
  integer, dimension(:), allocatable :: arr
end type structArray
type(structArray) :: b

I couldn't find in the Fortran standard why this behavior.. I expected that the size would be the size of the derived type to be the same size of the arr argument alone.

Squirrel
  • 23
  • 2
  • 2
    I don't think you will find statements about the underlying memory layout of the datatypes in the Fortran standards, as it is implementor's specific. – Rodrigo Rodrigues Feb 28 '23 at 15:22

1 Answers1

2

The Fortran standard doesn't specify such implementation details, it's up to the processor (compiler) to decide how the derived type is organized in memory (*)

Regarding the allocatable array, it's not a simple address (as it would be in C) but rather a full descriptor (a hidden type, somehow) that contains also the rank, the sizes, lower bounds, upper bounds... So in your case 64 bits is plausible (again, the standard doesn't specify how the descriptor is built).

(*) unless the sequence keyword is inserted before the component list. In that case, the compiler is required to store the components in the order of the list, and without internal padding (the type is then similar to a C struct).

PierU
  • 1,391
  • 3
  • 15
  • The `bind(c)` attribute also affects this, right? – Ross Feb 28 '23 at 15:54
  • 1
    Good answer, @PierU. Ross, if you need more details about the descriptor of allocatable variables, you can check in [this answer](https://stackoverflow.com/questions/45906545/check-if-array-is-allocatable-in-fortran/52898929#52898929), and if you need more details about the storage of derived types and sequence types, you can check [this one](https://stackoverflow.com/questions/50837394/behavior-of-components-when-structures-are-in-an-array/50841361#50841361). – Rodrigo Rodrigues Feb 28 '23 at 15:57
  • @Ross indeed `bind(C)` explicitely requires the compiler to organize the type in memory such that it is interoperable with a `struct` of the C companion compiler. – PierU Feb 28 '23 at 16:07