我有这个简单的 Fortran 代码和一个函数,我在主程序中明确提供了一个参数。代码如下:
implicit none
real*8 rrr,x
external tttt
x = rrr(10)
end
function rrr(seed)
integer seed, k
real*8 rrr
k = 7
seed = 16807 * ( seed - k * 127773 ) - (k * 2836)
print*,seed
rrr = seed / 2.
end
它可以编译,但是在运行时会产生以下错误:
Program received signal SIGBUS: Access to an undefined portion of a memory object.
Backtrace for this error:
#0 0x10f43bfe6
#1 0x10f43b7ac
#2 0x7fff89740529
#3 0x10f433d78
#4 0x10f433e2c
#5 0x10f433e6e
Bus error: 10
任何想法可能导致错误?我使用 gfortran 编译我的代码。
最佳答案
您正在修改函数中的种子。你不能这样做,因为它是恒定的 10
.您不能修改 seed
如果你在函数中传递了一些无法定义的东西。常量文字是不可定义的。变量通常是。
另外,不要使用外部函数。使用模块,或将您的函数放入包含部分,使其成为内部的。这样调用者将具有显式接口(interface)并可以检查代码的正确性。
特别是,如果您使用函数参数 intent(in)
,您所犯的错误可以自动避免。并检查接口(interface)。即使没有模块,如果您启用所有警告和错误检查,许多编译器也可以发现问题。例如 -g -fcheck=all -Wall -fbacktrace
在 gfortran 中。
为您修复:
real*8 :: x
integer :: iseed
iseed = 10
x = rrr(iseed)
contains
function rrr(seed)
real*8 :: rrr
integer, intent(in) :: seed
integer :: kk
k = 7
seed = 16807 * ( seed - k * 127773 ) - (k * 2836)
print *,seed
rrr = seed / 2.
end function
end program
关于fortran - 程序接收信号 SIGBUS : Access to an undefined portion of a memory object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38961864/