使用邻接表构造图时,Fortran中存在分段错误 [英] Segmentation fault in Fortran while constructing graph using adjacency lists
问题描述
我正在使用邻接列表方法创建图形.每个节点都表示为一个节点,该节点指向与其连接的其他节点.以下是我的代码
I am creating graph using the adjacency list method. Each node is represented as a node which points to other nodes connected to it. The following is my code
program main
use graphs
implicit none
type(node),pointer :: start
type(node), dimension(:), pointer :: grp
integer :: n, ios=0, a,b, i
open(1, file='test6.txt', status='OLD', action='READ')
read(1,*,iostat=ios) n
allocate(start)
allocate(grp(n))
do, i=1,n
grp(i)%val=i
enddo
do while(ios==0)
read(1,*, iostat=ios)a,b
if(ios.NE.0)then
exit
endif
start => grp(a)
call add(start, b)
start => grp(b)
call add(start, a)
end do
end program main
模块图如下
module graphs
type node
integer :: val
type(node), pointer :: next
end type node
contains
subroutine add(strt, nxn)
implicit none
type(node), pointer :: strt, new_node, lst
integer :: nxn
allocate(new_node)
allocate(lst)
lst => strt
new_node%val = nxn
new_node%next => NULL()
do while(associated(lst%next))
lst => lst%next
enddo
lst%next => new_node
end subroutine add
end module graphs
文件test6.txt
如下
43
1 2
1 10
2 3
2 11
3 4
4 5
5 6
6 7
7 8
8 9
3 12
4 13
5 14
6 15
7 16
8 17
9 18
10 11
11 12
12 13
13 14
14 15
15 16
16 17
17 18
10 19
11 19
12 20
我遇到以下错误
Program received signal SIGSEGV: Segmentation fault - invalid memory
reference
Backtrace for this error:
#0 0x7f786df6bef7 in ???
#1 0x7f786df6b12d in ???
#2 0x7f786dbbc4af in ???
#3 0x401db0 in __graphs_MOD_add
at /home/nav/MS project/new/grph.f90:18
#4 0x400f48 in ???
#5 0x400f85 in ???
#6 0x7f786dba782f in ???
#7 0x400a18 in ???
#8 0xffffffffffffffff in ???
Segmentation fault (core dumped)
上面的程序对于小图形运行平稳,但是对于大图形却不起作用.我无法弄错我在做什么?我正在使用gfortran编译器.
The above program is running smooth for small graphs but not working for large graphs. I am not able to get what am I doing wrong? I am using the gfortran compiler.
推荐答案
在代码中的任何地方都没有将起始%next
指针设置为null.因此,当您来到
Nowhere in your code you set the starting %next
pointer to null. So when you come to
do while(associated(lst%next))
lst%next
指向的地址未定义.您不允许询问它是否关联,因为返回的结果associated()
也是不确定的.另请参见此经典资源,以获取更多说明 http://www. cs.rpi.edu/~szymansk/OOF90/bugs.html#5
the address where lst%next
points to is undefined. You are not allowed to ask whether it is associated, because the result associated()
will return is also undefined. See also this classical resource for some more explanation http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html#5
最好的解决方法是默认初始化指针组件
The best cure is to the default initialization of pointer components
type node
integer :: val
type(node), pointer :: next => null()
end type node
养成始终将指针组件设置为null的习惯.
Make it a habit to always set pointer components to null.
这篇关于使用邻接表构造图时,Fortran中存在分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!