/ Published in: C++
The problem is that we don't know the size of the required output buffer. Providing a static buffer, no matter its size, runs a risk of overrunning the buffer.
This snippet uses vsnprintf() to output an sprintf() string based on a variable length parameter list to a dynamically allocated output buffer. The function is provided with the size of the output buffer, and it returns -1 if the buffer is not large enough. In this case, the code reallocates a larger buffer and attempts once again to output the string. The vsnprintf() will succeed when the buffer is large enough.
Expand |
Embed | Plain Text
void LogLine (const char *mask, const char* format, ...) { static bool firstTime = true; static char *outputBuffer = 0; static size_t outputBufferSize = 0; static size_t outputBufferSizeIncrement = (4 * 1024); if (firstTime) { firstTime = false; outputBufferSize = (16 * 1024); outputBuffer = new char [outputBufferSize]; } va_list argptr; va_start (argptr, format); int numCharsWritten = 0; while ((numCharsWritten = vsnprintf (outputBuffer, outputBufferSize, format, argptr)) < 0) { // <outputBuffer> not large enough to receive the output, increase the buffer outputBufferSize += outputBufferSizeIncrement; delete[] outputBuffer; outputBuffer = new char [outputBufferSize]; } va_end (argptr); . . . }
You need to login to post a comment.
