ifort and out of bound Index - Odd Behaviour

前端 未结 2 561
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 04:40

Recently I\'ve resumed Fortran and probably there\'s something I\'m missing but this behaviour looks very odd

When I run the following code (compiled with ifort), th

相关标签:
2条回答
  • 2020-12-20 05:35

    The compiler is not required to diagnose your out of bound indexing. When you do something like this, what happens is unspecified by the language standard. It is also known as undefined behaviour.

    You can't expect anything specific to happen.

    If you wish your error to be diagnosed, compile with error checking:

       ifort -g -traceback -warn -check yourcode.f90
    

    What actually happened is that you wrote something to some random place in memory. Who knows what would happened in a more complex code. It can then crash at random occasions or give wrong results.

    0 讨论(0)
  • 2020-12-20 05:43

    The compiled code does not normally check for bounds and out-of bounds access. You can expect the operating system killing the process if it tries to access memory outside of what is allocated to the process, but otherwise it will let it go. It is difficult to tell when this happens.

    In your case you set and accessed memory outside of the array bounds - it is actually a memory address so possible to instruct your code to do that - but it must have been within the memory allocated to the process, and as you found out, the result is unpredictable and undefined.

    You can enforce strict bound checking with ifort using the

    -check bounds
    

    compiler option. This will actually catch this error compile time for the ifort version I used. Gfortran catches the error even without any additional compiler flags.

    0 讨论(0)
提交回复
热议问题