在Fortran中自动进行数组重新分配 [英] Automatic array deallocation in Fortran

查看:226
本文介绍了在Fortran中自动进行数组重新分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用gfortran -std = f2008.我有一个函数,该函数返回包含可分配数组的派生类型.该函数在返回之前调用allocate().似乎在分配数组的函数返回并且我的程序出现段错误后的某个时间,数组正在自动释放.

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?

推荐答案

一个普遍的答案:可分配数组在超出范围时会自动取消分配.在外部范围中使用"结果后,将自动释放函数结果.当父派生类型变量超出范围或被释放时,可分配的组件将被释放.

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.

pointers,指向函数结果的对象在取消分配后未定义,并且不得使用.如果这样做,可能会导致您描述的问题.

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.

这篇关于在Fortran中自动进行数组重新分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆