This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
-Wformat-overflow works strangely with struct members
- From: Basin Ilya <basinilya at gmail dot com>
- To: gcc-help at gcc dot gnu dot org
- Date: Fri, 7 Jul 2017 16:05:19 +0300
- Subject: -Wformat-overflow works strangely with struct members
- Authentication-results: sourceware.org; auth=none
Hi.
According to the description of -Wformat-overflow=2, "Unknown string arguments ... are assumed to be 1 character long".
However, when I pass a struct member of unknown length as a string argument, it's assumed to have the maximum possible length. Besides, I get this warning only if it's not
the first argument.
#include <stdio.h>
extern struct {
char s[142];
} x;
extern char s[142];
int main(int argc, char *argv[]) {
char buf[12];
sprintf(buf, "%c%s", 'x', x.s); // why warning?
sprintf(buf, "%s", x.s); // why no warning then?
sprintf(buf, "%c%s", 'x', s); // why no warning then?
return 0;
}
_
$ gcc -c -Wformat-overflow=1 test.c
test.c: In function ‘main’:
test.c:11:18: warning: ‘%s’ directive writing up to 141 bytes into a region of size 11 [-Wformat-overflow=]
sprintf(buf, "%c%s", 'x', x.s); // why warning?
^~ ~
test.c:11:2: note: ‘sprintf’ output between 2 and 143 bytes into a destination of size 12
sprintf(buf, "%c%s", 'x', x.s); // why warning?
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
_
gcc (GCC) 7.1.1 20170528