1

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
}
Mandar
  • 1,006
  • 11
  • 28
  • not clear what you mean with " ignore string printing". Do you want to skip the output if it contains a `%` or do you want to print the string as is or do you want the string printed without the `%` ? – 463035818_is_not_an_ai Jul 26 '17 at 13:15
  • [You have the same issue with `printf`.](https://stackoverflow.com/questions/1860159/how-to-escape-the-sign-in-cs-printf). You need to escape it. You could C++-ify it and use streams instead. – NathanOliver Jul 26 '17 at 13:15
  • You could also supply an argument, not sure what it will do, but it should crash `Log("this test is%quick", "Please Run"); // ????` – Code Gorilla Jul 26 '17 at 13:17

2 Answers2

3

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.

Florian Winter
  • 4,750
  • 1
  • 44
  • 69
2

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

Code Gorilla
  • 962
  • 9
  • 23