3

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?

2
  • 1
    It seems like it really knows the members of standard struct tm , and treats tm::tm_mon+1 as an ordinary int. Commented Aug 17, 2024 at 10:58
  • 1
    Can't reproduce, pleas post a minimal reproducible example including any compiler flags. Commented Aug 17, 2024 at 11:08

1 Answer 1

1

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);
      |               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.