This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

-Wformat-overflow works strangely with struct members


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]