snprintf
This function requires a specified length, and the compiler will perform an out-of-bounds check, so it must be ensured that the target length is longer than the sum of all parameters. But consider the following procedure:
#include <stdio.h>
#include <string.h>
#define LENGTH 1024
int main() {
char cache[LENGTH];
memset(cache, 0, LENGTH);
snprintf(cache, sizeof(LENGTH), "%s/ruaruarua", cache);
return 0;
}
After opening this program-Wall
, an error will be reported:
test.c: In function ‘main’:
test.c:9:44: error: ‘/ruaruarua’ directive output truncated writing 10 bytes into a region of size 4 [-Werror=format-truncation=]
snprintf(cache, sizeof(LENGTH), "%s/ruaruarua", cache);
~~~~^~~~~~
test.c:9:5: note: ‘snprintf’ output 11 or more bytes into a destination of size 4
snprintf(cache, sizeof(LENGTH), "%s/ruaruarua", cache);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors
This error is expected because it is indeed possible to cross the boundary. So the question is, how can I complete the same function without reporting an error?
My gcc
version is relatively new, 7.1.1
. It is estimated that older versions of the compiler will not report this error.
First of all, the second parameter of
snprintf()
represents the size of the buffer, here it should beLENGTH
, the value ofsizeof(LENGTH)
is 4(I guess what you want to write should be
sizeof (cache)
bar). So, will it be OK after changing it tosnprintf(cache, LENGTH, "%s/ruaruarua", cache);
? Let’s look at this example:This example attempts to add a string to the end of
buf
, take a look at the outputDid not achieve the desired results. Why is this? There is this paragraph in the manual of
snprintf()
:So how do you "print your original content and some new content into an array"? One way is to set the buffer passed to
snprintf()
to the end of the string in the array:Then how to continuously add data to the end of the buffer? Notice that the function return value of the
printf()
family is the number of characters printed (number of characters printed), then you can call it like this:The result is