title: dangerous behavior of lapack routin zheev
body: <p>I stumbled upon an odd behavior when using the lapack routine <code>zheev()</code>. There are two issues which I do not understand</p>
  
  <p>1) One of my global variables seems to be overwritten by <code>zheev()</code>. The following small program shows it:</p>
  
  <p>[compiled with <code>gfortran -o test test.f90 -llapack -lblas</code>]</p>
  
  <pre><code>program test    
  implicit none
  
  integer, parameter :: dp = 8
  integer, parameter :: dim = 3
  
  integer :: l
  
  real(dp), parameter :: kmin = -0.03_dp
  real(dp), parameter :: kmax = 0.03_dp
  integer, parameter  :: steps = 100
  real(dp) :: stepD = (kmax - kmin)/real(steps)
  complex(dp) :: matrix(dim,dim)=0.
  
  integer :: info
  integer :: rwork=3*dim-2, lwork, lwmax=100
  real(dp) :: evals(dim) 
  complex(dp) :: work(3*dim-2)
  
  lwork=-1
  call zheev('N','U',size(matrix,1), matrix, dim, evals, work, lwork, &amp;
              rwork, info) 
  lwork = min( lwmax, int( work(1) ))
  
  do l = 0, 3
      write(*,*) stepD
      call zheev('N', 'U', size(matrix,1), matrix, dim, evals, work, &amp;
      lwork, rwork, info) 
      write(*,*) stepD
  end do
  
  end program test
  </code></pre>
  
  <p>The output is</p>
  
  <pre><code>5.9999999999999995E-004
     0.0000000000000000     
     0.0000000000000000     
     0.0000000000000000     
     0.0000000000000000     
     0.0000000000000000     
     0.0000000000000000     
     0.0000000000000000  
  </code></pre>
  
  <p>This can be cured by setting stepD to a parameter. But I do not understand this behavior. It is getting even more weird:</p>
  
  <p>2) Setting <code>lwork</code> in the definition to some value like</p>
  
  <pre><code>integer :: rwork=3*dim-2, lwork=10, lwmax=100
  </code></pre>
  
  <p>(simply change the corresponding line above)
  gives the following result:</p>
  
  <pre><code>   5.9999999999999995E-004
     5.9999991208314896E-004
     5.9999991208314896E-004
     5.9999991208314896E-004
     5.9999991208314896E-004
     5.9999991208314896E-004
     5.9999991208314896E-004
     5.9999991208314896E-004
  </code></pre>
  
  <p>How can this happen? Setting <code>lwork</code> to 10 should have no effect since later on it is set to -1. An important notion is: If one removes</p>
  
  <pre><code>lwork=-1
  call zheev('N','U',size(matrix,1), matrix, dim, evals, work, lwork, &amp;
              rwork, info) 
  lwork = min( lwmax, int( work(1) ))
  </code></pre>
  
  <p>the code works fine.</p>