title: deallocate of allocator in C++
body: <p>I've defined a class template Vec which holds a sequence of T like vector:</p>
  
  <pre><code>template &lt;typename T&gt; class Vec {
      public:
          size_t size() const { return first_free - elements; }
          size_t capacity() const { return cap - elements; }
          T *begin() const { return elements; }
          T *end() const { return first_free; }
          void resize(const size_t); // something wrong in this function
          ... 
      private:
          allocator&lt;T&gt; alloc; //allocates the elements
          T *elements; // pointer to the first element in the array
          T *first_free; // pointer to the first free element in the array
          T *cap; // pointer to one past the end of the array
          ...
  }; 
  </code></pre>
  
  <p>when my code calls this function, the programm will crash,</p>
  
  <pre><code>template &lt;typename T&gt; void Vec&lt;T&gt;::resize(const size_t newcap)
  {
      // this part goes well
      if(newcap &gt; capacity()) {
          auto newdata = alloc.allocate(newcap);
          auto dest = newdata;
          auto orig = elements;
          for(size_t i = 0; i != size(); ++i) 
              alloc.construct(dest++, std::move(*orig++));
          elements = newdata;
          first_free = dest;
          cap = elements + newcap;
      }
      // crash happens in the following two parts
      else if(size() &lt;= newcap &amp;&amp; newcap &lt; capacity()) { // deallocate the redundant memory where no element exists
         alloc.deallocate(elements + newcap, capacity() - newcap); // this line causes crash 
         cap = elements + newcap; 
      }   
      else if(size() &lt; newcap) { // destroy the elements and deallocate the memory
          for(auto p = first_free; p != elements + newcap; /*empty*/)
              alloc.destroy(--p);
          alloc.deallocate(elements + newcap, capacity() - newcap); // this line causes crash 
          first_free = cap = elements + newcap;
      }
  }
  </code></pre>
  
  <p>calling code:</p>
  
  <pre><code>Vec&lt;string&gt; v{"aaa", "bbb", "ccc"}; // size() == 3, capacity == 3
  v.resize(2); // to resize v to size() == 2, capacity == 2
  </code></pre>
  
  <p>I think I've made a right deallocate calling and correct pointer arithmetic. Thank you.</p>