Septacle
Septacle

Reputation: 277

Reading real*8 variable with value 0 with real*4 results a large number in fortran without warning

Reading real*4 variable with value 0 with real*8 results a large number, sometimes without warning.

I'm not good at Fortran. I was just running a Fortran code I got from someone else, and it made a segmentation fault. While I was debugging it, I found that one of the subroutines is reading a variable with value 0 defined with real*8 as real*4 results a large value.

I tried to reproduce it with simple code, but compiler showed a warning for the argument mismatch. I had to nest codes to reproduce the suppressed warning in simple code, but I'm not sure what's the exact condition for suppressed warning.

Actually, for some reason, I'm suspecting it may be the problem of my compiler, as the code (not the example code, original code) ran fine on the PC of the person who gave me the code.

file hello.f:

  implicit none
  call sdo()
  END

file test.f:

  subroutine sdo()
  implicit none
  real*4 dsecs
  dsecs=0
  write(0,*) dsecs
  call sd(dsecs)
  return
  end

file test2.f:

  subroutine sd(dsecs)
  implicit none
  real*8 dsecs
  write(0,*) dsecs
  return
  end

compilation and execution:

$ gfortran -o hello hello.f test.f test2.f
$ ./hello

Expected result:

0. 00000000
0. 0000000000000000

Actual results:

0. 00000000
-5.2153889789423361E+223

Upvotes: 1

Views: 433

Answers (1)

Amadan
Amadan

Reputation: 198486

It is not the problem of the compiler. It is the problem of the code. Your code did issue a warning for me that you were doing something nefarious, as it should. The subroutine that thinks dsecs is 4 bytes long sent 4 bytes. The subroutine that thinks dsecs is 8 bytes long looked at 8 bytes. What's in the other 4 bytes? Who knows. How does it look like when the two get mixed together? Probably not what you want. It's like accidentally getting served a scoopful of half icecream and half garbage: unlikely to taste the way you thought.

This is one of those problems that are very simply solved with that classic joke: "Doctor, doctor, it hurts when I do this!" - "Then... don't do that."

EDIT: Sorry, I cheated. I didn't compile them as separate programs. When I do, I don't get warnings. This is also normal - at compilation step, you didn't specify how foreign subroutines look so it couldn't complain, and at linking step compiler doesn't check any more.

Upvotes: 3

Related Questions