arrays - 如何判断 Fortran 数组指针是否已直接分配,或者与另一个对象关联?

标签 arrays pointers memory-leaks fortran fortran90

我正在使用包含一些数组指针的 Fortran 代码;根据用户输入,它们可以使用赋值语句 => 设置为指向另一个数组,也可以使用 allocate 语句直接分配。 p>

这会在代码末尾释放内存产生问题,因为在第一种情况下我只想无效指针,而在第二种情况下我需要释放 它可以防止内存泄漏。问题是,在这两种情况下,关联都返回true,所以我不知道如何在不手动跟踪的情况下判断我处于哪种情况。由于有很多这样的数组指针,我宁愿避免这样做。

有没有简单的方法来区分这两种情况?

谢谢!

最佳答案

这听起来像是一团糟。我假设你有这样的东西:

program really_bad
    implicit none
    integer, dimension(:), pointer :: a
    integer, dimension(:), allocatable, target :: b
    logical :: point_to_b

    allocate(b(10))
    write(*, *) "Should I point to B?"
    read(*, *) point_to_b

    if (point_to_b) then
        a => b
    else
        allocate(a(10))
    end if

    ! Destroy A

end program really_bad

你的问题是破坏性的部分。如果a指向b,那么您需要NULLIFY它,因为您需要保留b。但是,如果 a 没有指向 b,而您仅对其进行NULLIFY,则会出现内存泄漏。

正如 @ian-bush 指出的那样,您可以检查某事物是否与其他事物相关联,但这意味着您必须将指针与所有可能的目标进行比较,并且您声称您有很多这样的目标。

您可以尝试的一件事(但这可能是更糟糕的想法)是尝试解除分配,并使用其 STAT= 虚拟参数来检查解除分配是否真正有效。请注意,这是一个可怕的黑客攻击,我只让它在 Intel 上工作,而不是在 GFortran 上工作,但这里没有任何结果:

program don
    implicit none
    integer, dimension(:), pointer :: a
    integer, dimension(:), target, allocatable :: b
    logical :: point_to_b
    integer :: stat

    allocate(b(10))
    b = (/ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 /)
    write(*, *) "Should I point to B?"
    read(*, *) point_to_b
    if ( point_to_b ) then
        a => b
    else
        allocate(a(10))
    end if
    deallocate(a, stat=stat)
    if ( stat /= 0 ) nullify(a)
end program don

更好的方法可能是将数组指针替换为既具有指针又具有其关联方式的标志的类型。

program don
    implicit none
    type :: my_array_pointer_type
        integer, dimension(:), pointer :: array
        logical :: master
    end type my_array_pointer_type
    type(my_array_pointer_type) :: a
    integer, dimension(:), target, allocatable :: b
    logical :: point_to_b
    integer :: stat

    allocate(b(10))

    b = (/ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 /)
    write(*, *) "Should I point to B?"
    read(*, *) point_to_b
    if ( point_to_b ) then
        a%master = .false.
        a%array => b
    else
        a%master = .true.
        allocate(a%array(10))
    end if

    if (a%master) then
        deallocate(a%array)
    else
        nullify(a%array)
    end if
end program don

如果您可能将另一个指针指向a,然后尝试销毁它,那么这些建议都不会帮助您。在这种情况下,我真的建议重新考虑你的整个项目设计。

关于arrays - 如何判断 Fortran 数组指针是否已直接分配,或者与另一个对象关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38349061/

相关文章:

java - 字符串到字符数组和字符串数组

node.js - 确定 NodeJS 中 RSS 内存泄漏的原因

c - 代码中的这一行是什么意思? (指向字符的指针数组)?

pointers - 为什么 `offset_from` 使用的指针必须从指向同一对象的指针派生?

c - 链表节点初始化,不使用malloc()

c - 我用scanf获取输入,我用printf检查输入....然后我去用的时候输入不正确

javascript - 清除主干模型/集合内存泄漏

visual-c++ - IXMLDOMDocument 内存泄漏问题

ios - 从数组返回的属性创建常量

php - 如何在php中合并两个没有重复值的数组?