Vince W.
Vince W.

Reputation: 3785

Toy example of a segfault in Fortran

What is an example of code that deliberately causes a segfault in Fortran? I tried the following in msys, but all I got was a warning and the naughty access of the baddata array just printed 0.

I need this for learning purposes but also as a test case for writing code to handle gracefully when things like this happen when calling an external Fortran function

program segfault

  implicit none

  real, dimension(10) :: baddata
  integer i

  do i=1,10
     baddata(i) = 1.0
  end do

  print *, baddata(1)
  print *, baddata(1024)

end program segfault

compiled with: gfortran segfault.f90 -o sefault yields:

(base) C:\Coding\Fortran>gfortran segfault.f90 -o segfault
segfault.f90:13:19:

   13 |   print *, baddata(1024)
      |                   1
Warning: Array reference at (1) is out of bounds (1024 > 10) in dimension 1

(base) C:\Coding\Fortran>segfault
   1.00000000
   0.00000000

Upvotes: 0

Views: 148

Answers (1)

francescalus
francescalus

Reputation: 32366

As a general rule, you cannot do this "within Fortran".

Segmentation faults come from attempting to access parts of memory without permission. The Fortran language is specified in such a way that if you try to access a lump of memory without permission (such as accessing an array element not within bounds) then you don't have a valid Fortran program. That's part of the "not within Fortran". Another part is that if you have a (valid Fortran) program which correctly references things, then the processor is required to ensure that the program is treated in a correct way (which doesn't involve segmentation faults).

Any "toy example" with a segmentation fault is going to depend on specific behaviour of a particular compiler, operating system, and so on. These could vary depending on versions, compile- and run-time options.

For example, in this question we see how a simple attempt to access out-of-bounds access is detected by the compiler and even when running doesn't result in a segmentation fault. Other cases are in other questions, such as this one. More detail on when an array access results in a segmentation fault can be found in a related answer.

Why is this detection important? Well, if the compiler detects that you are attempting out-of-bounds access, then it could just as correctly, under the Fortran language, treat your

  print *, baddata(1024)

as though you'd written

  print *, -1231.516, "<- I hope you like this value I made up for you"

Perhaps your best bet would be to try the classic null dereference:

  integer, pointer :: i=>null()
  i=0
end

But this isn't a Fortran program. You may need to do a lot more work to get a reliable segmentation fault. This could move you well beyond a "toy" example.

Alternatively, if you can generate a SIGSEGV (again, this wouldn't be a Fortran thing), perhaps with a procedure not defined by Fortran, then you may find that easier.

Upvotes: 1

Related Questions