title: Segmentation fault with -O2 in Fortran
body: <p>While developing a large Fortran software I have now and again come across this error, in particular when compiling with -O2 to have a bit better performance.</p>
  
  <p>In some cases the error is real and can be corrected but in other cases I find no error and assume it is caused by -O2 shuffling around the code. As my old fashioned debugging technique is to add write statements close to the point where the error occurs have I found the error often disappeared when I did that. </p>
  
  <p>Maybe because the -O2 optimization is a bit careful shuffling around such statements. </p>
  
  <p>Recently I had this error in a loop which was not very complex and not very time critical and adding a write statement inside the loop prevented this error.  When I removed the write statement the error came back.  To avoid creating a lot of meaningless output while running the program I found it was sufficient to write to an internal character so for a user nothing changed.  </p>
  
  <p>There was no error when compiling the code without -O2 but the loop is inside a module using many local variables and I do not know how to compile one subroutine in a module separately without -O2.</p>
  
  <p>I am using GNU Fortran 7.2.0 on Linux and Windows (this recent error occurred only on Linux but previously I have had similar problems with Windows).  I do not have access to any other compilers but my code is free and has been compiled with other compilers with no problems reported.</p>
  
  <p>So my question is if one can turn off -O2 for a small part of the code inside a module or if there are better alternatives than adding write statements to prevent -O2 to shuffle around the code inside a particular subroutine.</p>