Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Mismatches between arguments and conversion specifications may result in undefined behavior. Many compilers can diagnose type mismatches in formatted output function invocations.

Code Block
bgColor#ffcccc
langc
const char *error_msg = "Resource not available to user.";
int error_type = 3;
/* ... */
printf("Error (type %s): %d\n", error_type, error_msg);

...

This compliant solution ensures that the format arguments match their respective format specifications.

Code Block
bgColor#ccccff
langc
const char *error_msg = "Resource not available to user.";
int error_type = 3;
/* ... */
printf("Error (type %d): %s\n", error_type, error_msg);

...

Passing them as any other type leads to undefined behavior. In this noncompliant code example, the width and precision are specified using parameters declared to be of size_t type. These are unsigned types that may not be the same size as int.

Code Block
bgColor#ffcccc
langc
int print_int(int i, size_t width, size_t prec) {
  int n;

  n = printf("%*.*d", width, prec, i);

  return n;
}

...

In this compliant solution, the field width and precision arguments to printf() format directives are of type int.

Code Block
bgColor#ccccff
langc
int print_int(int i, int width, int prec) {
  int n;

  n = printf("%*.*d", width, prec, i);

  return n;
}

...