Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Potential issue with not using format specifier with printf

Tags:

c

printf

  #include <stdio.h>
  void wrapperPrint(char* s)
  {
      printf(s);
      return;
  }

  int main()
  {

          wrapperPrint("Hello world\n");
          wrapperPrint("This is a string");

      return 0;
  }

If the program prints strings correctly (it does, tested on gcc 4.6.3) , why do we need format specifiers like %d, %s etc. Or in other words, what is the potential problem with this program.

like image 294
Anon Avatar asked Dec 06 '25 19:12

Anon


1 Answers

As-is, there's no problem at all. If, however, you pass in a string containing a percent-sign, that could cause a problem, because printf would try to treat it as the beginning of a conversion specifier, but 1) the rest of the conversion specifier probably won't be there, and 2) you won't have passed a matching argument when you call printf either, so if you do pass a proper conversion specifier, it'll try to use a nonexistent argument (giving undefined behavior).

like image 155
Jerry Coffin Avatar answered Dec 08 '25 11:12

Jerry Coffin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!