nicer snprintf() behavior

metadata
Wenzel Jakob 2010-09-07 22:24:48 +02:00
parent 11a47e1851
commit 4d8cc8d764
2 changed files with 30 additions and 7 deletions

View File

@ -48,19 +48,30 @@ void Logger::log(ELogLevel level, const Class *theClass,
if (level < m_logLevel)
return;
char tmp[2048];
char tmp[512], *msg = tmp;
va_list iterator;
va_start(iterator, fmt);
vsnprintf(tmp, 2048, fmt, iterator);
size_t size = vsnprintf(tmp, sizeof(tmp), fmt, iterator);
va_end(iterator);
if (size >= sizeof(tmp)) {
/* Overflow! -- dynamically allocate memory */
msg = new char[size+1];
va_start(iterator, fmt);
vsnprintf(msg, size+1, fmt, iterator);
va_end(iterator);
}
if (m_formatter == NULL) {
std::cerr << "PANIC: Logging has not been properly initialized!" << std::endl;
exit(-1);
}
std::string text = m_formatter->format(level, theClass,
Thread::getThread(), tmp, file, line);
Thread::getThread(), msg, file, line);
if (msg != tmp)
delete[] msg;
if (level < EError) {
m_mutex->lock();

View File

@ -311,14 +311,26 @@ Float log2(Float value) {
return std::log(value) * invLn2;
}
std::string formatString(const char *pFmt, ...) {
char tmp[2048]; /* Limited to 2k */
std::string formatString(const char *fmt, ...) {
char tmp[512];
va_list iterator;
va_start(iterator, pFmt);
vsnprintf(tmp, 2048, pFmt, iterator);
va_start(iterator, fmt);
size_t size = vsnprintf(tmp, sizeof(tmp), fmt, iterator);
va_end(iterator);
if (size >= sizeof(tmp)) {
/* Overflow! -- dynamically allocate memory */
char *dest = new char[size+1];
va_start(iterator, fmt);
vsnprintf(dest, size+1, fmt, iterator);
va_end(iterator);
std::string result(dest);
delete[] dest;
return result;
}
return std::string(tmp);
}