Fortran递归分段错误 [英] Fortran recursion segmentation faults

查看:171
本文介绍了Fortran递归分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须设计和实现一个Fortran程序来确定正方形网格上簇的大小,并且递归编写子程序似乎非常方便。然而,每当我的晶格尺寸增长超过一定的值(大约200 /边)时,子程序始终发生段错误。这是我的集群检测例程:

  RECURSIVE SUBROUTINE growCluster(lattice,adj,idx,area)
INTEGER,INTENT (INOUT):: lattice(:),area
INTEGER,INTENT(IN):: adj(:, :),idx

lattice(idx)= -1
面积=面积+ 1

IF(lattice(adj(1,idx))。GT.0)&
CALL growCluster(lattice,adj,adj(1,idx),area)

IF(lattice(adj(2,idx))。GT.0)&
CALL growCluster(lattice,adj,adj(2,idx),area)

IF(lattice(adj(3,idx))。GT.0)&
CALL growCluster(lattice,adj,adj(3,idx),area)

IF(lattice(adj(4,idx))。GT.0)&
CALL growCluster(lattice,adj,adj(4,idx),area)
END SUBROUTINE growCluster

其中adj(1,n)表示站点n的北邻居,adj(2,n)表示西等等。什么会导致不规则的段错误行为?对于大的晶格大小,集群是太大吗?

我认为你正在运行一个堆栈溢出。如果你的格子每边超过200单位,那就是40,000单位,这意味着你要递归40,000次。根据你的堆栈大小和你的堆栈帧大小,你可能会很容易地耗尽堆栈空间。



您必须将算法转换为使用较少堆栈的算法空间为了处理更大的格子。 维基百科提供了一些关于如何进行洪水填充而不吹风的实现(以伪代码形式)你的堆栈。


I have to design and implement a Fortran routine to determine the size of clusters on a square lattice, and it seemed extremely convenient to code the subroutine recursively. However, whenever my lattice size grows beyond a certain value (around 200/side), the subroutine consistently segfaults. Here's my cluster-detection routine:

RECURSIVE SUBROUTINE growCluster(lattice, adj, idx, area)
    INTEGER, INTENT(INOUT)  :: lattice(:), area 
    INTEGER, INTENT(IN)     :: adj(:,:), idx

    lattice(idx) = -1
    area = area + 1

    IF (lattice(adj(1,idx)).GT.0) &
        CALL growCluster(lattice,adj,adj(1,idx),area)

    IF (lattice(adj(2,idx)).GT.0) &
        CALL growCluster(lattice,adj,adj(2,idx),area)

    IF (lattice(adj(3,idx)).GT.0) &
        CALL growCluster(lattice,adj,adj(3,idx),area)

    IF (lattice(adj(4,idx)).GT.0) &
        CALL growCluster(lattice,adj,adj(4,idx),area)
END SUBROUTINE growCluster

where adj(1,n) represents the north neighbor of site n, adj(2,n) represents the west and so on. What would cause the erratic segfault behavior? Is the cluster just "too huge" for large lattice sizes?

解决方案

I think you're running into a stack overflow. If your lattice is over 200 units per side, that's 40,000 units, which means you're recursing 40,000 times. Depending on your stack size and your stack frame size, you could easily be running out of stack space.

You'll have to convert your algorithm into one that uses less stack space in order to handle larger lattices. Wikipedia provides a few implementations (in pseudocode) on how to do a flood fill without blowing your stack.

这篇关于Fortran递归分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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