title: "Bus Error" and "munmap_chunk(): Invalid Pointer" in Fortran 95
body: <p>I'm working on a python project which calls a fortran subroutine via f2py for efficiency reasons.</p>
  
  <p>When I execute the code, it fails at seemingly random (non-consistent) points with Segmentation Fault errors. Using the <code>faulthandler</code> Python library, I have narrowed my search down to a <code>Bus Error</code> and <code>munmap_chunk(): Invalid Pointer</code> errors, though the errors are still not consistent.</p>
  
  <p>Given the seemingly random nature of the error I'm afraid I can't provide a MWE. My Fortran code is (abridged -- full version <a href="https://pastebin.com/ba41gYih" rel="nofollow noreferrer">here</a>):</p>
  
  <pre><code>module event_rates
        contains
        subroutine event_rate_f95(events, edges, events_edges, lifetimes, lt_size, NBins)
              implicit none
              ! define input parameters
              ! define internal variables
  
              dtd = delay_time_distribution(lifetimes, edges, NBins)
              print *, "DTD generated"
              do i = 1, NBins+1
                    t1 = events_edges(i-1)
                    t2 = events_edges(i)
                    print *, "Ts done"
  
                    z1 = estimate_redshift(t1)
                    z2 = estimate_redshift(t2)
  
                    print *, 'computing sfr'
  
                    SFR = compute_SFR(z1, z2) / (1E-3) ** 3
  
                    print *, "about to enter inner loop"
  
                    do j = 0, i-1
                          ! do a computation
                    enddo
  
                    print *, "exited inner loop"
                    print *, i
              enddo
        end subroutine
  end module event_rates
  </code></pre>
  
  <p>Where <code>delay_time_distribution, estimate_redshift, compute_SFR</code> are functions I define earlier. For reference, <code>NBins</code> is approximately 50 whenever I call this. In the 3 most recent executions, it failed at:</p>
  
  <p>1) <code>i=20</code> inside <code>estimate_redshift()</code>,</p>
  
  <p>2) In the <code>delay_time_distribution()</code> function,</p>
  
  <p>3) After the Fortran code had terminated and returned control back to Python.</p>
  
  <p>From reading background information on these errors, it appears to be a memory management problem, as Segmentation Faults are accessing memory I can't access, Bus Errors are accessing memory that isn't there, and <code>munmap_chunk()</code> is passing the wrong pointer to a FREE instruction. But I'm relying on Fortran 95's inbuilt memory management to handle this for me. Monitoring <code>htop</code> while code is executing shows me that my CPU usage on one core spikes, but memory usage stays constant.</p>
  
  <p>My question is two-fold: what is causing these errors, and how can one debug this further in general?</p>