Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Moreover, *psz may point to an already-allocated string (on the heap), which may potentially be used during the formatting. </p> </blockquote> <p>For <code>*psz</code> to be potentially reusable, some indication of whether it's garbage or a valid heap pointer is needed. Given no function argument indicating that, you can assume the only sane convention of a NULL sentinel value.... i.e. if <code>*psz</code> is not NULL, then you can reuse it provided that the data you wish to format can fit into the same space. As the function is not given any indication of the amount of memory previous allocated, you can either: - use realloc and trust it to avoid needless movement of the buffer - infer a minimum pre-existing buffer size from <code>strlen()</code> - this would mean that if you're say writing a long string then a short string then the original long string into the buffer, the last operation will needlessly replace the buffer.</p> <p>Clearly realloc is a better bet.</p> <pre><code>int StrPrintF(char **psz, const char *szFmt, ...) { va_list args; int nLen; va_start(args, szFmt); if ((nLen = vsnprintf(NULL, 0, szFmt, args)) &gt;= 0) { char *szRes = (char*) realloc(psz, nLen + 1); // ^ realloc does a fresh allocation is *psz == NULL if (szRes) vsnprintf(*psz = szRes, nLen + 1, szFmt, args); // can't fail // ^ note the assignment.... else nLen = -1; } va_end(args); return nLen; } </code></pre> <p>Note too - from a Linux manpage for <code>printf()</code> - if your <code>sprintf()</code> doesn't return a useful length you've got to get/write an implementation that does....</p> <blockquote> <p>Concerning the return value of snprintf(), SUSv2 and C99 contradict each other: when snprintf() is called with size=0 then SUSv2 stipulates an unspecified return value less than 1, while C99 allows str to be NULL in this case, and gives the return value (as always) as the number of characters that would have been written in case the output string has been large enough.</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload