fortran - Assigning a value to a variable passed to a function causes a segmentation fault. -
this question has answer here:
consider simple program:
program foo integer bar,idum print * , bar(1) end program function bar(idum) integer idum,bar print * , idum idum = 2 bar = 2 return end
when run it, segmentation fault upon line idum = 2
starting program: /tmp/a.out 1 program received signal sigsegv, segmentation fault. 0x000000000040081b in bar (idum=1) @ play.f:11 11 idum = 2
am not allowed assign values variables passed function? how can use them flags?
you pass literal value 1
function. try change in
idum = 2
that not allowed. code tries change literal constant , crashes, because not possible.
if want change value inside function, a) must variable, not constant value, b) must passed value (fortran 2003).
in modern fortran always use explicit interfaces. mean always. either use modules (preferred!!!), or, in simple cases, use internal functions like:
program foo integer bar,idum print * , bar(1) contains function bar(idum) integer idum,bar print * , idum idum = 2 bar = 2 return end function end program
the compiler may able tell you doing wrong. so, if specify intent
argument:
function bar(idum) integer bar integer, intent(in) :: idum
the compiler will complain now. complain other intent's. , can fix code make compiler happy.
and always!!!!! use implicit none
. not optional. necessary.
Comments
Post a Comment