Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

fortran - Segfault when calling a function with a constant argument

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...