Skip to content

Undefined behavior when the specified width is INT_MIN #232

Description

@eyalroz

(Due to @afonsojanu in #231:)

If we call:

printf_("%*d", INT_MIN, 5);

we're passing a width due to the use of *. Now, when the argument is negative, format_string_loop() negates it so it can fall through the usual positive-width-plus-left-justify path:

else if (*format == '*') {
  const int w = va_arg(args, int);
  if (w < 0) {
    flags |= FLAGS_LEFT;
    width = (printf_size_t)-w;
  }
  ...

and with w being INT_MIN, -w overflows - which is undefined behavior in C89, I'm pretty sure. The C99 standard quote is (emphasis mine):

§6.5 Expressions

  1. If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions