Guest User

Untitled

a guest
Oct 16th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. //static
  2. bool OTString::vformat(const char * fmt, va_list * pvl, std::string & strOutput)
  3. {
  4. OT_ASSERT(NULL != fmt);
  5. OT_ASSERT(NULL != pvl);
  6. // ------------------
  7. va_list args;
  8. int size;
  9. int nsize;
  10. char * buffer;
  11.  
  12.  
  13. #ifdef _WIN32
  14.  
  15. args = *pvl;
  16. nsize = _vscprintf(fmt,args);
  17.  
  18. #else
  19.  
  20. size = 512;
  21. buffer = new char[size+100]; // probably could just be size, not size+1. But harmless.
  22. OT_ASSERT(NULL != buffer);
  23. OTPassword::zeroMemory(buffer, size+100);
  24. // ------------------------------------
  25. // Here the buffer is 513 bytes but we tell vsnprintf that it's 512 bytes.
  26. // I guess only for wiggle-room.
  27. //
  28.  
  29. va_copy(args, *pvl);
  30. nsize = vsnprintf(buffer,size,fmt,args);
  31.  
  32. delete buffer; buffer = NULL;
  33.  
  34. #endif
  35.  
  36. va_end(args);
  37. OT_ASSERT(nsize >= 0);
  38.  
  39. // fail -- delete buffer and try again
  40. // If nsize was 1024 bytes, then that would mean that it printed 1024 characters,
  41. // even though the actual string must be 1025 in length (to have room for the null
  42. // terminator.)
  43. // If size, the ACTUAL buffer, was 1024 (that is, if size <= nsize) then size would
  44. // LACK the necessary space to store the 1025th byte containing the null terminator.
  45. // Therefore we are forced to delete the buffer and make one that is nsize+1, so that
  46. // it will be 1025 bytes and thus have the necessary space for the terminator
  47. //
  48.  
  49. size = nsize+1;
  50. buffer = new char[size+100];
  51. OT_ASSERT(NULL != buffer);
  52. OTPassword::zeroMemory(buffer, size+100);
  53.  
  54. // ------------------------------------
  55. #ifdef _WIN32
  56. nsize = vsnprintf_s(buffer,size,size,fmt,*pvl);
  57. #else
  58. nsize = vsnprintf(buffer,size,fmt,*pvl)
  59. #endif
  60. // ------------------------------------
  61.  
  62. OT_ASSERT( nsize >= 0 );
  63. OT_ASSERT( size > nsize);
  64.  
  65. // ------------------------------------
  66. // If nsize was 1024, that means the actual string is stored in
  67. // 0..1023 and the null terminator must be stored at index 1024,
  68. // in the 1025th byte. (Remember, we count from 0.)
  69. // (Therefore, since nsize is 1024 already, we can use it as the
  70. // index for adding the null terminator.)
  71. //
  72. // Update: Valgrind is complaining about a 1 byte issue in this function,
  73. // so I'm commenting this out for now. Anyway, vsnprintf should null-terminate.
  74. //
  75. // buffer[nsize] = '\0';
  76. // ------------------------------------
  77. strOutput = buffer; // set buffer
  78. delete buffer; buffer = NULL;
  79. return true;
  80. }
Add Comment
Please, Sign In to add comment