Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

snprintf confusion

Tags:

c

string

printf

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?

like image 450
amin__ Avatar asked Jun 05 '12 09:06

amin__


People also ask

Is Snprintf slow?

snprintf is still not fast in general (lots of overhead parsing the format string and passing varargs through wrapper functions).

What is Snprintf function?

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.

What is the return value of Snprintf?

The snprintf() function returns the number of bytes that are written in the array, not counting the ending null character.

Is Sprintf safe to use?

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.


1 Answers

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.

like image 82
CB Bailey Avatar answered Nov 03 '22 23:11

CB Bailey