Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does g++ detect format-overflow

With gcc version 13.2.0 (Ubuntu 13.2.0-23ubuntu4) the following code compiles OK:

char mm[3]; sprintf (mm, "%02d", date_struct->tm_mon); // tm_mon is from 0 to 11

How does gcc know that tm_mon fits in 2 digits? Does it know the range restriction 0..11?

And the following code raises a warning:

char mm[3]; sprintf (mm, "%02d", date_struct->tm_mon+1);

directive writing between 2 and 11 bytes into a region of size 3

Does gcc "forget" the range?

like image 901
malaise Avatar asked Aug 07 '26 04:08

malaise


1 Answers

Does gcc "forget" the range?

Yes.

It's surprising to me that gcc knows the range of tm_mon, but not surprising that it loses that range once tm_mon is turned into an expression.

In theory gcc could keep tracing through such expressions at compile time, but eventually that becomes equivalent to the halting problem, so stopping as soon as the first + (or -) is encountered seems reasonable to me.

Surprisingly, using 1000 * date_struct->tm_mon does not result in a warning (but should). So this entire warning appears to be half-cooked.


Here is a minimal repro:

#include <stdio.h>
#include <time.h>

#ifndef XXX
#define XXX 0
#endif

void fn(struct tm *date_struct) {
  char mm[3]; sprintf (mm, "%02d", date_struct->tm_mon + XXX);
}
gcc --version
gcc (GCC) 14.2.1 20240801 (Red Hat 14.2.1-1)
...

gcc -c -Wall tt.c
 # no output

gcc -c -Wall tt.c -DXXX=1
tt.c:9:29: warning: ‘%02d’ directive writing between 2 and 11 bytes into a region of size 3 [-Wformat-overflow=]
    9 |   char mm[3]; sprintf (mm, "%02d", date_struct->tm_mon + XXX);
      |                             ^~~~
tt.c:9:28: note: directive argument in the range [-2147483647, 2147483647]
    9 |   char mm[3]; sprintf (mm, "%02d", date_struct->tm_mon + XXX);
      |                            ^~~~~~
tt.c:9:15: note: ‘sprintf’ output between 3 and 12 bytes into a destination of size 3
    9 |   char mm[3]; sprintf (mm, "%02d", date_struct->tm_mon + XXX);
      |               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
like image 167
Employed Russian Avatar answered Aug 08 '26 17:08

Employed Russian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!