Reputation: 2289
In my code I use the following line to print a char readbuffer[1];
array (char array with size 1):
printf(readbuffer);
This compiles and works without an issue on my pc (Arch Linux, gcc version 7.3.1+20180406-1
). However, when I submitted my assignment containing this code to my instructor, he in fact got a compiler warning compiling my code:
shell.c:89:20: warning: format not a string literal and no format arguments [-Wformat-security]
printf(readbuffer);
He is using the gcc/clang version from 16.04 LTS release. We both used the same compiler flags.
Why is this? Is this suddenly not an issue anymore in the new gcc
version? If so, why not?
Just a note: I don't want to know how to solve this issue, but just want to know why the warning is inconsistent over gcc versions.
Upvotes: 1
Views: 2325
Reputation:
This is not caused by a difference in GCC versions. Rather, Ubuntu has modified GCC to enable -Wformat -Wformat-security
by default. If you pass those options on Arch Linux, you should see the same behaviour there.
Upvotes: 2
Reputation: 881093
I don't want to know how to solve this issue ...
Yes, you really do!
Unless your char[1]
variable always contains \0
, what you are doing is unsafe. And. if it does contain that, what you are doing is nothing :-)
The correct way to do what you're trying to do is, assuming a need for printf
:
printf("%.1s", readbuffer);
This will ensure you don't try to read past that single character. Of course, if you know that there will always be a character, just use:
putchar(*readbuffer);
In terms as to why different gcc
versions report differently, that can be put down to simple improvement over time. It's the same reason why, for example, gcc
will complain about mismatch between number of format specifiers and number of arguments in something like:
printf ("%s %d\n", "hello");
whereas some other implementations may not.
Specifically, while the standard mandates what must be reported as a diagnostic, it does not otherwise limit what implementations may report as a diagnostic beyond that.
Later versions of a compiler may add or remove these optional diagnostics, or change how they decide to report on them.
Upvotes: 2