user1173240
user1173240

Reputation: 1475

vsntprintf_s crashes if input string contains "%"

I have an error logging mechanism, which constructs a buffer using vsntprintf_s. Unfortunately it so happens that if it sees a "%" symbol, then there is an exception while constructing the buffer.

TCHAR szBuffer[2000];
    if (lpszFormat !=  NULL)
        _vsntprintf_s(szBuffer, _countof(szBuffer), lpszFormat, args);

Whole function -

bool someFunction::TraceLog (LPCTSTR lpszFormat, ...)
{

    va_list args = nullptr;
    va_start (args, lpszFormat);

TCHAR szBuffer[2000];
    if (lpszFormat !=  NULL)
        _vsntprintf_s(szBuffer, _countof(szBuffer), lpszFormat, args);
    else
        _tcsncpy_s (szBuffer, _T("NULL format for TraceGen"), _TRUNCATE);
}

where, if the input string, lpszFormat contains a '%' it fails. The "%" is not meant to be an operator, but is rather for something within the string itself. E.g. Test%Test

What can be the best way to handle this?

Upvotes: 0

Views: 618

Answers (1)

Dialecticus
Dialecticus

Reputation: 16759

The best way to handle this is to always have format string under your control (and by you I mean the code that you write). You must not have a format string like "Test%Test", because that is against the rules for a format string.

If you want to print that exact string then corresponding format string should be "Test%%Test".

If the contents of the string is not under your control then the format string should just be "%s" and the actual string should be given as function's next parameter.

Upvotes: 1

Related Questions