How to suppress sprintf() warning 'directive writing between 1 and 11 bytes into a region of size 6 '
with
sprintf(tag, "Literal - %d", literal);
since your buffer is 16 bytes, and the prefix is 10 bytes, that leaves 5 bytes to write the string representation of literal
.
Since int
is probably 32 bit on your system, it ranges up to 2147483647 and negative-wise -2147483648 (11 characters), the compiler warns you (since it was able to compute all the sizes)
Now since you know that the range cannot be outside 0-255, just reduce literal
size by, for instance, declaring it as unsigned short
(short
can be 6 bytes long as a string: -32768
as chux noted in comments) so you have leeway for your value.
unsigned short literal = 123;
sprintf(tag, "Literal - %hu", literal);
(you could use unsigned char
which ranges exactly from 0 to 255, using %hhu
format specifier)
or just cast when printing:
sprintf(tag, "Literal - %hu", (unsigned short)literal);
(%u
probably works too, but depends on how smart the compiler is: is it analysing just the format or the size of variable args?)
Let's not forget the most obvious solution now that we know why the warning occurs: let's define the array with a large enough size.
char tag[25]; // 21 would have been okay
should do it. Shaving it too close isn't generally a good idea, unless you're running out of ressources.
This warning is valid because tag
is not large enough to hold all possible values of the string to be constructed.
An integer, assuming 32 bits, needs up to 11 characters to store its string representation. There are 10 characters written to tag
before the integer value, so there are 6 bytes left to write other data. That's what the warning is telling you.
Since literal
has a range of 0 to 255, you can cast the value to unsigned char
and use %hhu
for the format specifier, which states that the argument is an unsigned char
.
In general sprintf
is considered unsafe, as it doesn't check the bounds of its ouput array. You should consider using snprintf
instead when writing into a fixed size buffer:
snprintf(tag, sizeof(tag), "Literal - %d", literal);