I am confused with snprintf function. First of all I have not found the function snprintf in a turbo C version compiler under stdio.h Secondly in a GNU compiler snprintf is returning -1 when buffer size is smaller than formatted string ,though it should return the number of characters would have been printed if buffer size was sufficiently large. I have following source :
#include<stdio.h>
int main()
{
char str[100];
int numchar = snprintf(str,2,"ello jdj");
printf("%d\n",numchar);
return 0;
}
This code should output 8 according to as I know about snprintf so far. but it is returning -1 in my GNU compiler. What are the facts behind?
snprintf is still not fast in general (lots of overhead parsing the format string and passing varargs through wrapper functions).
The snprintf() function formats and stores a series of characters and values in the array buffer. The snprintf() function accepts an argument 'n', which indicates the maximum number of characters (including at the end of null character) to be written to buffer.
The snprintf() function returns the number of bytes that are written in the array, not counting the ending null character.
Security is less in sprintf as it does not protect the string if it is more than 255 characters. And if a null character is present, there is a chance of modification of string.
It sounds like you are using an old version of glibc. From the man page for snprintf
:
The glibc implementation of the functions snprintf() and vsnprintf() conforms to the C99 standard, that is, behaves as described above, since glibc version 2.1. Until glibc 2.0.6 they would return -1 when the output was truncated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With