how to use vasprintf() with special characters (%)?

3.1k views Asked by At

I have the following sample code.

#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>

int test(const char *fmt,...)
{
        va_list args;
        char *vacmd=NULL;

        va_start(args,fmt);
        vasprintf(&vacmd, fmt, args);
        printf("vacmd is %s\n", vacmd);

        return 0;
}

int main(void)
{
        int ret = 0;
        char *cmd="@wilso%nqw";
        ret = test(cmd);
}

Output is :

vacmd is @wilsoqw

It removed the %n from the string. So my question is does vasprintf() works with specials characters or not? or am I missing something?

1

There are 1 answers

0
Sourav Ghosh On

For printf() and family functions,

Each conversion specification is introduced by the character %.

So, the % in a format string has a special meaning when used with printf()/scanf() family. You can use %% to discard the special meaning.

To quote the standard in this regard, from fprintf() function specification

%

A % character is written. No argument is converted. The complete conversion specification shall be %%.


FWIW, your current code exhibits undefined behaviour, as "If there are insufficient arguments for the format, the behavior is undefined." As per your code, there is no argument supplied for %n format specifier.