Invalid format specifiers in scanf (or) printf

As for the printf function, I understand the following from several links and experiments.

  • When we try to print an integer value using format specifiers that are used for float (or) double and vice versa, the behavior is unpredictable .
  • But you can use %c to print the equivalent character of an integer value. It is also acceptable to use %d to print the ASCII value (integer representation) of a character.

Similarly, what is scanf behavior if there is a mismatch in the format specifier and the arguments passed to scanf . Do standards set?

+4
source share
2 answers

Variad arguments (those that correspond to an ellipsis, ... ) are supported by default. This means that all shorter integral types are promoted to int (or unsigned, if necessary). There is no difference between inte & shy; gers and characters ( I believe ). The difference between %d and %c in printf is simply formatting the value.

scanf is another fish maker. All arguments that you pass are pointers. There are no defaults and shy; mo & shy; tion among pointers, and it is very important that you pass in a specifier of the exact format that matches the pointee type.

In any case, if your format specifier does not match the argument provided (for example, passing int * to %p to printf ), the result is undefined behavior, which is much worse than "unpredictable" - this means that your program is simply poorly formed.

+4
source

First, due to promotion, a type that conforms to the conversion specification may not match the type that is passed to the function. For example, characters are promoted to int, so printf ("% c") really expects an int, which is then passed to an unsigned char. Passing int directly has the same effect as passing that was entered into an unsigned char, and therefore is safe.

If the argument does not have the expected type, for example, if you pass a float instead of an integer, then the result will be undefined.

This is especially disastrous with scanf () because the arguments are pointers. If you pass, tell the pointer to char, when the function expects a pointer to a float, then the function will try to write (say) 4 bytes to 1 byte, which is bad. You may well get segfault.

0
source

Source: https://habr.com/ru/post/1439035/


All Articles