-1

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
avishkar
  • 19
  • 1
  • 2
  • 3
    you need `"%%"`, since `"%n"` itself is a conversion specifier. – The Paramagnetic Croissant Jun 18 '15 at 13:57
  • 2
    You don't want to use `vasprintf`, or you did not read its documentation on [vasprintf(3)](http://man7.org/linux/man-pages/man3/vasprintf.3.html) – Basile Starynkevitch Jun 18 '15 at 13:58
  • 3
    I wish we had a close reason on RTFM and/or common sense. Seriously, just think about it. If all conversion specifiers start with `%`, then how **possibly** could poor `printf()` magically read your mind and deduce that you didn't *intend* to use one particular `%` character as a formatting command? – The Paramagnetic Croissant Jun 18 '15 at 14:00
  • 1
    @TheParamagneticCroissant Also, If I'm not wrong, the present code exhibits UB, due to missing argument to `%n`, right? – Sourav Ghosh Jun 18 '15 at 14:27
  • 2
    @SouravGhosh exactly. – The Paramagnetic Croissant Jun 18 '15 at 14:58
  • @TheParamagneticCroissant Note: poor `printf()` still is unable to print `'\0'` from a format string - - certainly not much of a loss though. C _could_ have specified `"%\0"` to print `'\0'`, but _that_ would run into trouble with the definition of a format _string_. IAC, poor `printf()` has many issues and its overworked and under appreciated. Would not surprise me if it went on strike. – chux - Reinstate Monica Jun 18 '15 at 15:35
  • "You don't want to use vasprintf" Why not? What would you suggest instead? – Daniel Ryan Sep 08 '16 at 23:44

1 Answers1

2

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261