Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //static
- bool OTString::vformat(const char * fmt, va_list * pvl, std::string & strOutput)
- {
- OT_ASSERT(NULL != fmt);
- OT_ASSERT(NULL != pvl);
- // ------------------
- va_list args;
- int size;
- int nsize;
- char * buffer;
- #ifdef _WIN32
- args = *pvl;
- nsize = _vscprintf(fmt,args);
- #else
- size = 512;
- buffer = new char[size+100]; // probably could just be size, not size+1. But harmless.
- OT_ASSERT(NULL != buffer);
- OTPassword::zeroMemory(buffer, size+100);
- // ------------------------------------
- // Here the buffer is 513 bytes but we tell vsnprintf that it's 512 bytes.
- // I guess only for wiggle-room.
- //
- va_copy(args, *pvl);
- nsize = vsnprintf(buffer,size,fmt,args);
- delete buffer; buffer = NULL;
- #endif
- va_end(args);
- OT_ASSERT(nsize >= 0);
- // fail -- delete buffer and try again
- // If nsize was 1024 bytes, then that would mean that it printed 1024 characters,
- // even though the actual string must be 1025 in length (to have room for the null
- // terminator.)
- // If size, the ACTUAL buffer, was 1024 (that is, if size <= nsize) then size would
- // LACK the necessary space to store the 1025th byte containing the null terminator.
- // Therefore we are forced to delete the buffer and make one that is nsize+1, so that
- // it will be 1025 bytes and thus have the necessary space for the terminator
- //
- size = nsize+1;
- buffer = new char[size+100];
- OT_ASSERT(NULL != buffer);
- OTPassword::zeroMemory(buffer, size+100);
- // ------------------------------------
- #ifdef _WIN32
- nsize = vsnprintf_s(buffer,size,size,fmt,*pvl);
- #else
- nsize = vsnprintf(buffer,size,fmt,*pvl)
- #endif
- // ------------------------------------
- OT_ASSERT( nsize >= 0 );
- OT_ASSERT( size > nsize);
- // ------------------------------------
- // If nsize was 1024, that means the actual string is stored in
- // 0..1023 and the null terminator must be stored at index 1024,
- // in the 1025th byte. (Remember, we count from 0.)
- // (Therefore, since nsize is 1024 already, we can use it as the
- // index for adding the null terminator.)
- //
- // Update: Valgrind is complaining about a 1 byte issue in this function,
- // so I'm commenting this out for now. Anyway, vsnprintf should null-terminate.
- //
- // buffer[nsize] = '\0';
- // ------------------------------------
- strOutput = buffer; // set buffer
- delete buffer; buffer = NULL;
- return true;
- }
Add Comment
Please, Sign In to add comment