Segfault when calling a function with a constant argument

前端 未结 5 446
一个人的身影
一个人的身影 2020-12-21 13:58

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)
  im         


        
5条回答
  •  执笔经年
    2020-12-21 14:32

    Your code has done nothing to tell the compiler that the declaration

    real ran3
    

    refers to the function you define later in your source file. To the compiler you have declared a real variable called ran3. Once the compiler has read the end statement at the end of the program it can bugger off and drink mojitos if it wants to, it is not bound to do any more compilation -- though you might find that some compilers do.

    A general rule in structuring Fortran programs is that the compiler must encounter the definition of an entity (variable, function, subroutine, derived-type, what-have-you) before it encounters any use thereof. Your code has broken this rule.

    Once the code has declared a real variable it tries, in this statement,

    write(*,*) ran3(0)
    

    to access the 0-th element of an array called ran3 and it all ends in tears.

    The quick fix would be to move end program su to the end of the source file, and to put a line containing the keyword contains before the definition of the function. You could then delete the declaration real ran3 as the compiler will take care of any linking that needs to be done.

    Oh, and while I'm writing, you could do yourself, and those trying to comprehend your code, a favour by paying more attention to formatting what you have posted. Personally (opinion coming up, look away now if you are easily upset) I would fire any programmer who turned in code looking like that on the grounds that anyone who pays so little attention to the small stuff probably doesn't pay much attention to the big stuff either.

提交回复
热议问题