title: How can I know the real maximum size of a vector? (Not using std::vector::max_size)
body: <p>On an online course I am learning about vectors. In one of the examples they explained that: <code>std::vector::max_size()</code> should give me the maximum size the vector can reach. I decided to test it:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;
  #include &lt;exception&gt;
  #include &lt;vector&gt;
  
  int main(void) {
      std::vector &lt;int&gt; nums;
      int max = nums.max_size();
      std::cout &lt;&lt; "Max: " &lt;&lt; max &lt;&lt; std::endl;
      for (int i = 0; i &lt; max; i++) {
          try {
              nums.push_back(i);
          }
          catch (std::bad_alloc ex) {
              std::cerr &lt;&lt; ex.what() &lt;&lt; std::endl;
              std::cout &lt;&lt; "Failed at: " &lt;&lt; i &lt;&lt; std::endl;
              break;
          }
      }
  
      return 0;
  }
  </code></pre>
  
  <p>And this is the result of running it:</p>
  
  <pre><code>Max: 1073741823
  bad allocation
  Failed at: 204324850
  </code></pre>
  
  <p>It was 869416973 ints short. </p>
  
  <p>So I started googling it. <a href="http://www.cplusplus.com/reference/vector/vector/max_size/" rel="noreferrer">Here</a> I read that it returns the "the maximum potential size the container can reach", and adds "but the container is by no means guaranteed to be able to reach that size". I would have imagined that it would fail, but not by that much. It just got 1/5 of the way before failing. Why is <code>std::vector::max_size</code> so off? And what I see of more importance, is there a way of really knowing the potential size of a vector?</p>