https://gcc.gnu.org/bugzilla/show_bug.cgi?id=107277

            Bug ID: 107277
           Summary: Spurious -Wformat-overflow when combined with
                    __builtin_expect()
           Product: gcc
           Version: 12.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: tomerv at gmail dot com
  Target Milestone: ---

Incorrect format-overflow warning/error:

  error: '%d' directive writing between 1 and 11 bytes into a region of size 10
[-Werror=format-overflow=]
  note: directive argument in the range [-2147483648, 5]         

On this code:

  __attribute((__noreturn__)) void do_panic();
  int get_number();

  #define unlikely(x)     __builtin_expect((x),0)

  int foo()
  {   
      char buff[10]={0};
      int index = get_number();

      if (unlikely(index < 0)) {  // <-- index cannot be negative
          do_panic();
      }

      if (6 <= index) {
          index = 0;
      }

      int n = sprintf(buff, "%d", index);
      if (unlikely(n < 0)) {
          do_panic();
      }

      return n;
  }

Removing "unlikely" from the first condition fixes the issue.

Also - and this is a missing warning, which is the reverse problem - removing
the whole "if (6 <= index)" block removes the warning, but only with the
"unlikely" present.

https://godbolt.org/z/9esTTTbGq

Reply via email to