With avr-gcc 14, the compiler gives this warning:
avrenv.c: In function ‘main’
avrenv.c:12:13: warning: ‘strncpy’ output may be truncated copying 255 bytes from a string of length 509 [-Wstringop-truncation]
12 | strncpy(dest, src[i], 255);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~
for this (minimal reproducer):
#include <stdint.h>
#include <stdio.h>
#include <string.h>
int main(void) {
while (1) {
char src[2][255] = {{'a', '\0'}, {'b', '\0'}};
for (uint8_t i = 0; i < 2; i++) {
char dest[255];
strncpy(dest, src[i], 255);
puts(dest);
}
}
return 0;
}
The warning is however only given with -O2, with for example -O1 or no optimization, there is no warning. It seems that x86-64 gcc does the same.
I am just curious - why is the warning given with -O2, and why length 509?