title: Getting an EXC_BAD_ACCESS error when trying to sort a bag
body: <p>So I am trying to get the count of words in a file and insert that into a bag.  To improve processing times, I created a replace command that takes a reference to that object and switch it with the one before it so more common words are quicker to be incremented in the bag.  I am continually getting EXC_BAD_ACCESS Code 2 errors but am unaware of how these are created.  Below are the code blocks in question.</p>
  
  <pre><code>template&lt;typename T&gt;
  void replace(T&amp; item, T&amp; item2)
  {
      T value = item;
      T value2 = item2;
      item = value2;
      item2 = value;
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>template&lt;typename T, int N&gt;
  void Bag&lt;T,N&gt;::add(T item)
  {
      for (int i = 0; i &lt; m_size; i++)
      {
          if (m_items[i] == item)
          {
              m_counts[i]++;
              while (i != 0 &amp;&amp; m_counts[i] &gt; m_counts[i-1]) {
                  replace(m_items[i], m_items[i-1]);
                  replace(m_counts[i], m_counts[i-1]);
                  i--;
              }
              return;
          }
      }
      m_items [m_size] = item;
      m_counts[m_size] = 1;
  
      m_size++;
  }
  </code></pre>
  
  <p>I read that it might be an infinite loop causing this but the while loop created should not be creating an infinite loop.  Any help is appreciated.  If the entire code needs to be posted, it can be found at:</p>
  
  <p>Github Gist of code
  <a href="https://gist.github.com/nohe427/ff1ce9bbeec78983aec3" rel="nofollow">https://gist.github.com/nohe427/ff1ce9bbeec78983aec3</a></p>