Starting with gcc 8, it will emit a warning if it can determine if a strn* call could be truncated. An example would be:
char buf1[1024];
char buf2[128];
char buf3[1024]
snprintf(buf1, sizeof(buf1), “buf2: %s buf3: %s”, buf2, buf3);
The compiler can determine that buf2 is of size 128, and the format string is adding 10 bytes to it and buf3 is 1024 more bytes. It is possible to put 1162 bytes into a 1024 buffer and force snprintf() to truncate it.
@mkaro has done a wonderful job silencing all of gcc’s warnings. We are having a disagreement on how to silence this warning though. His solution is to force the truncation via string precision.
So you have a situation like the following:
snprintf(buf1, sizeof(buf1), “buf2: %s buf3: %*s”, buf2, sizeof(buf1) - strlen(buf2) - strlen(buf3) - 10, buf3)
This basically moves where the truncation is happening. The buffer will still be truncated. We’ve done the math and forced the field width to be the max size it can be. It will be truncated there, instead of letting snprintf() do its thing. It is the same result, a bit more expensive and harder to program (not to mention it is uglier).
We have turned on -Werror, so this warning needs to be silenced in some way.
I find the warning not too helpful. As a developer, I usually oversize my buffers, but have a general idea of what I’m putting into them. The thing I put into buf2 or buf3 is generally much smaller than the size of the buffer. The truncation that snprintf() will do is to catch me if I am wrong. I don’t need to have the compiler telling me that it is possible that I could truncate. If that happens, it happens.
My solution is to just to ignore the warning. It’s easy enough to tell gcc to not emit this warning.
@mkaro’s opinion (he can correct me if I am wrong) is that we should not ignore any of gcc -Wall’s warnings. They are there for a reason.
I want to hear more opinions. Is this warning of great benefit to the codebase? Is it worth the hassle of silencing it in the code? Or should we just ignore the warning and leave things alone.
Bhroam