Deallocation of array with allocated elements

Deallocation of array with allocated elements

I have a data structure with allocated (inner) array elements. I also have an allocated (outer) array of these data structures. If I deallocate the outer array, will the inner array elements in the data structure also be dealocated or does that need to be done first to prevent a memory leak?

4 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.

The inner arrays will be automatically deallocated.  This is one of many advantages of allocatable arrays over pointers.  It should be impossible to create a memory leak with allocatables - this is by design.

Retired 12/31/2016


A point of clarification.  We have a simulator that we sometimes convert to a MATLAB MEX file.  When the simulator returns to MATLAB, it does not deallocate the allocated arrays because the program does not actually terminate.  This has forced us to write termination routines that deallocate everything explicitly.  Stupid MATLAB...  ;-)


Marshall, your situation seems a bit different from what mattsdad asked about.

I assume that your simulator is a collection of Fortran procedures that you call from MATLAB - are they in a DLL? If allocatable arrays are declared local to a routine (perhaps the entry point to your simulator) and not in a module, then they will be deallocated when that routine exits. Otherwise, you are correct in saying that they need to be deallocated explicitly.  Or you can check on the next entry to see if they are already allocated, and if so, deallocate them first.

Retired 12/31/2016

Leave a Comment

Please sign in to add a comment. Not a member? Join today