Anon
Anon

Reputation: 2656

Potential issue with not using format specifier with 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.

Upvotes: 2

Views: 389

Answers (4)

Tim
Tim

Reputation: 5367

You should use puts(), or do printf("%s", s);

If the format string just happens to contain %s or any other format, then printf will try to read arguments that you did not pass, attempt to access random pieces of memory, and the result is not defined.

Try running your program with %s passed in and see what happens. Then try running it again under valgrind to really see the horrible thing that is happening.

Upvotes: 2

Alok Save
Alok Save

Reputation: 206526

why do we need format specifiers like %d, %s etc?

printf is not format safe. t does not understand type on its own,You have to explicitly tell printf the format(type) of your data arguments.It tells print how you want the argument to be interpreted as, If you don't it just treats it as an string(as in your example code).

Note that if there is a mis-match in the format specifier and the actual data type then what you get is Undefined Behavior.

Upvotes: 4

Jerry Coffin
Jerry Coffin

Reputation: 490128

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).

Upvotes: 6

nhahtdh
nhahtdh

Reputation: 56809

There is nothing that mandates the use of format specifier in printf. Rather, it is because you want to print string according to some format that you use printf. You may use other methods (puts) to output plain string.

For the program above, if there are format specifiers in the string, the program will print garbage, since you will still be calling printf underneath.

Upvotes: 1

Related Questions