user3578925
user3578925

Reputation: 941

Program received signal SIGBUS: Access to an undefined portion of a memory object

I have this simple Fortran code and a function which I explicitly supply with an argument in the main program. The code is below:

   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

It compiles, however upon run it produces the following error:

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

Any ideas what maybe causing the error? I use gfortran to compile my code.

Upvotes: 4

Views: 9633

Answers (1)

You are modifying the seed in the function. You cannot do that, because it is constant 10. You cannot modify seed in the function if you pass something, which is not definable into it. A constant literal is not definable. Variables normally are.

Also, don't use external functions. Use modules, or put your functions into the contains section which makes them internal. That way the caller will have explicit interface and can check correctness of the code.

In particular the error you made can be avoided automatically if you make the function argument intent(in) and check the interfaces. Even without modules many compilers can find out the problem if you enable all warnings and error checks. For example -g -fcheck=all -Wall -fbacktrace in gfortran.

Fix for you:

   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

Upvotes: 2

Related Questions