3

我有这个简单的 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 编译我的代码。

4

1 回答 1

2

您正在修改函数中的种子。你不能这样做,因为它是恒定的10seed如果您传递一些无法定义的内容,则无法在函数中进行修改。常量文字是不可定义的。变量通常是。

另外,不要使用外部函数。使用模块,或将您的函数放入包含部分,使其成为内部的。这样调用者将具有显式接口并可以检查代码的正确性。

特别是,如果您创建函数参数intent(in)并检查接口,则可以自动避免您犯的错误。即使没有模块,如果您启用所有警告和错误检查,许多编译器也可以发现问题。例如-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
于 2016-08-15T19:49:56.703 回答