title: Getting required buffer length with secure _vsnprintf_s
body: <p>I'm trying to update some "legacy" code to comply with the latest security updates to MSVC, and am facing some trouble migrating from <code>_vsnprintf</code> to <code>_vsnprintf_s</code>.</p>
  
  <p>In particular, I was calling <code>_vsnprintf</code> with a null buffer and zero for the count/length, getting the result, allocating a buffer of the needed size (<code>return value + 1</code>), and then calling <code>_vsnprintf</code> again with the newly-allocated buffer and known-correct size:</p>
  
  <pre><code>size_t length = _vsntprintf(nullptr, 0, mask, params);
  TCHAR *final = new TCHAR [length + 1];
  _vsntprintf(final, length + 1, mask, params);
  </code></pre>
  
  <p>This behavior is <a href="https://msdn.microsoft.com/en-us/library/1kt27hek.aspx?f=255&amp;MSPPError=-2147217396" rel="noreferrer">documented on MSDN</a>:</p>
  
  <blockquote>
    <p>If the buffer size specified by count is not sufficiently large to contain the output specified by format and argptr, the return value of vsnprintf is the number of characters that would be written if count were sufficiently large. If the return value is greater than count - 1, the output has been truncated.</p>
  </blockquote>
  
  <p>I'm trying to do the same with <code>_vsnprintf_s</code>, but <a href="https://msdn.microsoft.com/en-us/library/d3xd30zz.aspx" rel="noreferrer">its documentation does not contain the same</a>. It instead says</p>
  
  <blockquote>
    <p>If the storage required to store the data and a terminating null exceeds sizeOfBuffer, the invalid parameter handler is invoked, as described in Parameter Validation, unless count is _TRUNCATE, in which case as much of the string as will fit in buffer is written and -1 returned.</p>
  </blockquote>
  
  <p>Trying it out anyway with the following:</p>
  
  <pre><code>size_t length = _vsntprintf_s(nullptr, 0, 0, mask, params);
  </code></pre>
  
  <p>This results in a "length" of zero. If you pass in <code>_TRUNCATE</code> (-1) as the count instead, the following assertion fails:</p>
  
  <blockquote>
    <p>Expression: buffer != nullptr &amp;&amp; buffer_count > 0</p>
  </blockquote>
  
  <p>I presume it is possible to override <code>_set_invalid_parameter_handler</code> and somehow find out what the length should be, but there has to be an easier way?</p>