I was doing update outdated exercises. When I see “what’s changed”, only UNITY_BEGIN and UNITY_END stub was changed, and actual test cases were not changed.
However, after I click “Update Exercise”, my solution couldn’t accepted anymore.
This is error message:
./clock.c: In function 'number_to_clock':
./clock.c:15:22: error: '%02d' directive writing between 2 and 9 bytes into a region of size 6 [-Werror=format-overflow=]
15 | sprintf(r.text, "%02d:%02d", n / 60, n % 60);
| ^~~~
./clock.c:15:21: note: directive argument in the range [-35791370, 23]
15 | sprintf(r.text, "%02d:%02d", n / 60, n % 60);
| ^~~~~~~~~~~
./clock.c:15:21: note: directive argument in the range [-59, 59]
./clock.c:15:5: note: 'sprintf' output between 6 and 14 bytes into a destination of size 6
15 | sprintf(r.text, "%02d:%02d", n / 60, n % 60);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors
make: *** [makefile:37: tests.out] Error 1
This is related code:
static clock_t number_to_clock(int n) {
clock_t r;
n %= 1440;
if (n < 0) n += 1440;
sprintf(r.text, "%02d:%02d", n / 60, n % 60);
return r;
}
It seems that the compiler is complaining like “Hey, n / 60
and n % 60
can be (technically) negative. If then, your r.text
could suffer buffer overflow. I can’t allow such code”
I don’t think this is possible. AFAIK, the result of n %= 1440
is -1439 <= n <= 1439
, and then after if (n < 0) n += 1440;
, n should be 0 <= n <= 1439
.
I think the compiler is trying to be too smart and generated false warning, and then warning treats as error by compiler setting.