title: Why does this OpenCV code segfault?
body: <p>I'm preparing to parallelize some of my C++ OpenCV code.  I've come across a segfault, and I can't understand what's happening.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>class ExhaustiveComparisonMT
  {
      vector&lt;Mat&gt; *m_sigs;
      Mat *m_dist;
  public:
      ExhaustiveComparisonMT(vector&lt;Mat&gt; sigs, Mat dist)
      {
          m_sigs = &amp;sigs;
          m_dist = &amp;dist; // gdb breakpoint 1 here
      }
  
      void operator() (size_t last_row, size_t last_col) const
      {
          Mat diff = (*m_sigs)[0].clone(); // segfault happens here, gdb breakpoint 2 here
          for (size_t i = 0; i != last_row; ++i)
          for (size_t j = 0; j != last_row; ++j)
          {
              cv::absdiff((*m_sigs)[i], (*m_sigs)[j], diff);
              m_dist-&gt;at&lt;double&gt;(i, j) = cv::sum(diff).val[0];
          }
      }
  };
  
  void
  exhaustive_comparison(vector&lt;Mat&gt; sigs, Mat dist)
  {
      size_t width = sigs.size();
      ExhaustiveComparisonMT ecmt(sigs, dist);
      ecmt(width, width);
  }
  </code></pre>
  
  <p>Basically, an vector of matrices is being passed to the constructor.  A pointer to the vector is kept as a member variable, so the vector can be accessed again in <code>exhaustive_comparison</code>.  However, that function trips up trying to access the first element of the vector.</p>
  
  <p>I've tried to diagnose the problem with gdb by putting two breakpoints (see code).  At breakpoint 1:</p>
  
  <pre><code>(gdb) p (*m_sigs)[0]
  $1 = (cv::Mat &amp;) @0x7fffee77d010: {flags = 1124024325, dims = 2, rows = 1, cols = 712, data = 0x624ec0 "", refcount = 0x0, datastart = 0x624ec0 "", dataend = 0x6259e0 "", 
    datalimit = 0x6259e0 "", allocator = 0x0, size = {p = 0x7fffee77d018}, step = {p = 0x7fffee77d060, buf = {2848, 4}}}
  </code></pre>
  
  <p>Therefore, the first element is being accessed correctly.  Now, we go to breakpoint 2 and try the same thing:</p>
  
  <pre><code>(gdb) p (*m_sigs)[0]
  $2 = (cv::Mat &amp;) @0x7fffee77d010: &lt;error reading variable&gt;
  </code></pre>
  
  <p>The first element appears to be no longer accessible!  Its address is the same (0x7fffee77d010).  What's going on here?</p>
  
  <p>Finally, if I step forward, I get:</p>
  
  <pre><code>Program received signal SIGSEGV, Segmentation fault.
  0x00007ffff7a0dd50 in cv::Mat::copyTo(cv::_OutputArray const&amp;) const () from /usr/local/lib/libopencv_core.so.2.4
  </code></pre>
  
  <p>OpenCV tries to access the first element to clone it, and fails.</p>
  
  <p>Why is the first element accessible in the constructor, but not accessible in the <code>exhaustive_comparison</code> member function?</p>