Reputation: 125
I have the code below. After running the cppcheck tool, it reports an error as Buffer is accessed out of bounds? An error is reported on line with the snprintf.
#include <stdio.h>
int main(int argc, char * argv[])
{
if (argc > 1) {
char testref[8] = "";
snprintf(testref, sizeof(testref), "Ref:%s", argv[1]);
printf("===>testref=%s\n", testref);
}
}
below the command line interaction :
amin@ubuntu:$ gcc test.c -o test
amin@ubuntu:$
amin@ubuntu:$ ./test hello_world
===>testref=Ref:hel
amin@ubuntu:$ cppcheck test.c
Checking test.c...
[test.c:7]: (error) Buffer is accessed out of bounds.
amin@ubuntu:$
Is cppcheck correct to report this error?
Upvotes: 3
Views: 741
Reputation: 5094
I think, generally speaking, cppcheck is correct to report this error. The behavior of the snprintf
function is implementation-dependent, and in some implementations it is not guaranteed that a null-character is written if the string is too large for the buffer. In such case, the consecutive call to printf()
would read outside the boundaries of the buffer.
I could find at least one example of a snprintf
implementation that would result in out-of-bound errors for your code. And according to this comment it was also the case for True64/DigitalUnix before c99.
It would be interesting to see if cppcheck also reports an error for the following code (it should not report an error):
#include <stdio.h>
int main(int argc, char * argv[])
{
if (argc > 1) {
char testref[8] = "";
int ret = snprintf(testref, sizeof(testref), "Ref:%s", argv[1]);
if (ret >= 0) {
printf("===>testref=%s\n", testref);
}
}
}
Also note that Cppcheck version 1.82 does not report the error for your code. I'm not sure why version 1.72 does report the error and version 1.82 doesn't.
Upvotes: 2