Posted By

moshe on 05/21/12


Tagged


Versions (?)

Performing sprintf without overflowing the buffer


 / 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.

  1. void LogLine (const char *mask, const char* format, ...)
  2. {
  3. static bool firstTime = true;
  4. static char *outputBuffer = 0;
  5. static size_t outputBufferSize = 0;
  6. static size_t outputBufferSizeIncrement = (4 * 1024);
  7.  
  8. if (firstTime)
  9. {
  10. firstTime = false;
  11. outputBufferSize = (16 * 1024);
  12. outputBuffer = new char [outputBufferSize];
  13. }
  14.  
  15. va_list argptr;
  16. va_start (argptr, format);
  17.  
  18. int numCharsWritten = 0;
  19.  
  20. while ((numCharsWritten = vsnprintf (outputBuffer, outputBufferSize, format, argptr)) < 0)
  21. {
  22. // <outputBuffer> not large enough to receive the output, increase the buffer
  23. outputBufferSize += outputBufferSizeIncrement;
  24. delete[] outputBuffer;
  25. outputBuffer = new char [outputBufferSize];
  26. }
  27.  
  28. va_end (argptr);
  29. . . .
  30. }

Report this snippet  

You need to login to post a comment.