The code:
#include <stdio.h>
void Print(char str[100])
{
printf("%s", str);
}
int main(void)
{
Print("A");
}
When compiled with GCC 11.1 and above produces the warning
warning: 'Print' accessing 100 bytes in a region of size 2 [-Wstringop-overflow=]
when I pass it a smaller string. This is without any warning flags enabled.
Sample code: https://godbolt.org/z/nWs1PK9Y6
As you can see other compilers do not compain about this.
I did found a thread with a related issue but regarding an int array, which is even stranger:
GCC 11 gives -Wstringop-overflow when no string operation is used
However this is definitely a bug, was corrected, and does not occur anymore in tip-of-trunk version whereas in the code I show it still has the same warning in trunk.
I believe this to be another bug, or at least a not very useful warning as, to best of my knowledge, that argument will decay to a pointer, but I wanted to confirm that.
As stated in the comment section this can be useful to warn the API user that a smaller string is being passed as argument, but does it really make sense, at least to have it being showed with no warning flags enabled?
Passing a string to larger array is trivial in other situations. To me it would make more sense to warn the user if the passed string was larger than what the parameter is supposed to take, but if I pass a string larger than 100, the warning goes away.
CodePudding user response:
The
-Wstringop-overflow=4
option uses type-three Object Size Checking to determine the sizes of destination objects. At this setting the option warns about overflowing any data members, and when the destination is one of several objects it uses the size of the largest of them to decide whether to issue a warning. Similarly to-Wstringop-overflow=3
this setting of the option may result in warnings for benign code.
source: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
If char str[100]
was char str[]
, then gcc would automatically changes it to char *
.
This warning can be suppressed by using optimization flag -O2
or -O3
.