gsdx: Fix vsnprintf usage in format function

-1 is only returned when there is an encoding error, and the va_list
argument is indeterminate after being passed to vsnprintf.

Use the return value to determine the buffer length, and call va_end and
then va_start before vsnprintf is called again.
This commit is contained in:
Jonathan Li 2017-03-21 20:29:09 +00:00
parent ae2e8469b4
commit f174d71ac7
2 changed files with 10 additions and 23 deletions

View File

@ -28,35 +28,22 @@
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
string format(const char* fmt, ...)
std::string format(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
int result = -1, length = 256;
char* buffer = NULL;
while(result == -1)
{
if(buffer) delete [] buffer;
buffer = new char[length + 1];
memset(buffer, 0, length + 1);
result = vsnprintf(buffer, length, fmt, args);
length *= 2;
}
int size = vsnprintf(nullptr, 0, fmt, args) + 1;
va_end(args);
string s(buffer);
assert(size > 0);
std::vector<char> buffer(std::max(1, size));
delete [] buffer;
va_start(args, fmt);
vsnprintf(buffer.data(), size, fmt, args);
va_end(args);
return s;
return {buffer.data()};
}
#ifdef _WIN32

View File

@ -365,7 +365,7 @@ using namespace std;
#endif
extern string format(const char* fmt, ...);
extern std::string format(const char* fmt, ...);
extern void* vmalloc(size_t size, bool code);
extern void vmfree(void* ptr, size_t size);