且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用常量参数调用函数时的段错误

更新时间:2022-10-15 16:29:00

我发现代码有两个问题.第一个是我认为是错误原因的那个.函数 ran3 以常量 0 作为实际参数引用,但对应的虚拟参数 iseed 用于赋值的左侧函数中的声明.这是一个错误:您不能更改零的值.

第二个错误是ran3返回了一个real*8(不管是什么;这是一个非标准的声明),但是在主程序中声明了ran3作为默认的real.

以下程序和函数使用 gfortran 4.7.2 编译.

程序苏隐式无真实的::ran3写(*,*)运行3(0)结束程序 su函数ran3(iseed)隐式无整数:: iseed, temp真实的::ran3温度 = iseed * 153941 + 1ran3 = 温度 * 2.328 + 0.5结束函数ran3

I have written this very simple code in Fortran:

program su
  implicit none
  real ran3
  write(*,*) ran3(0)
end program su

real*8 function ran3(iseed)
  implicit none
  integer iseed
  iseed=iseed*153941+1
  ran3=float(iseed)*2.328+0.5     
end function ran3

I have no problem in compiling it but when I execute the code I get this message:

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

Backtrace for this error:
#0  0xB76BAC8B
#1  0xB76BB2DC
#2  0xB77BA3FF
#3  0x8048653 in ran3_
#4  0x80486B3 in MAIN__ at der.f90:?
Segmentation fault (core dumped)

Could you please tell why, and how I can solve it?

I see two problems with the code. The first is the one which I think is the cause of the error. The function ran3 is referenced with the constant 0 as the actual argument, but the corresponding dummy argument iseed is used on the left side of an assignment statement in the function. This is an error: you can't change the value of zero.

The second error is that ran3 returns a real*8 (whatever that may be; it's a non-standard declaration), but in the main program ran3 is declared as being a default real.

The following program and function compile with gfortran 4.7.2.

program su
    implicit none
    real :: ran3

    write(*, *) ran3(0)
end program su

function ran3(iseed)
    implicit none
    integer :: iseed, temp
    real :: ran3

    temp = iseed * 153941 + 1
    ran3 = temp * 2.328 + 0.5
end function ran3