Mandar
Mandar

Reputation: 1044

How can i avoiding crashing at vsprintf_s() while printing character similar to "%q"

There is a crash in vsprintf_s when we try to print "%q" in string statement. This crash can be avoided by using 2 symbols "%%q"

Is there any way to ignore string printing instead of crashing?

#include <windows.h>
#include <stdio.h>

#define LOG_LEN 1024

void Log( const CHAR * lpszFormat, ...)
{
        CHAR localBuff[2 * LOG_LEN + 1] = { 0 };
        va_list argp;

        va_start(argp, lpszFormat);
        vsprintf_s(localBuff, lpszFormat, argp);
        va_end(argp);

       ///...

       ///...

}

int main()
{
    Log("this test is quick");  // this works
    Log("this test is%quick");  // this Crashes
}

Upvotes: 1

Views: 987

Answers (2)

Florian Winter
Florian Winter

Reputation: 5299

If your format string containing the % is hard-coded in your application's code, then you just have to manually escape it as %%. It will be displayed as a single %.

If the % sign in the format string is dynamic data (and potentially user input), then it shouldn't be part of the format string at all! You should call

Log("%s", data.c_str());

instead of

Log(data);

Otherwise, you are opening for potential security holes in your application where users (or other potential attackers) can provoke crashes like the one you are experiencing.

Upvotes: 3

Code Gorilla
Code Gorilla

Reputation: 980

It crashed because you are using a % which means there will be an argument after the format string. The fact %q is rubbish doesn't matter it is looking for the first argument in the list.

If you want to print % the you must escape it with another %

Log("this test is%%quick");  // this will not crash

You will only get one % in the output

Upvotes: 2

Related Questions