The sprintf
() function belongs to the printf()
family of functions. In this module, we are going to discover more about this function and how we can use it in our programs.
Defining the sprintf() function
The Linux Man Pages for sprintf() defines it as :
#include <stdio.h>
int sprintf(char *str, const char *format, ...);
Basically sprintf() stands for “String Print”. Unlike standard printf() which write to stdout, sprintf stores output on the character buffer supplied to it. Let’s breakdown the definition a bit.
int
– The first thing you probably notice is theint
at the beginning of our function definition which refers to the return type of the function and can be used for error handling during programming ! The man pages describe the RETURN VALUE of the function as :
Upon successful return, the functions return the number of characters printed (excluding the null byte used to end output to strings).
If an output error is encountered, a negative value is returned.
- sprintf – The function name!
- char *str – This is a pointer to a character array that stores the resultant string
- const char *format – This contains the string which is to be written to the buffer. This also supports the use of format specifiers in C to get more comprehensive results and store them into the buffer.
Example Implementation of sprintf()
#include <stdio.h>
void main()
{
char buffer[20];
sprintf(buffer,"The Buffer Size Is : %d\n",sizeof(buffer));
printf("%s",buffer);
}
Output :
The Buffer Size Is : 20
Explaining The Output
- First we declare the header file which contains the definition of sprintf() as :
#include <stdio.h>
- Next we declare a character array by the name of ‘buffer’ to store our string :
char buffer[20];
- Now, we can call our sprintf() function. Here, to demonstrate the use of format specifiers, we shall use the %d format specifier to display the size of our buffer
sprintf(buffer,"The Buffer Size Is : %d\n",sizeof(buffer));
- Finally print the string stored in buffer using printf()
printf("%s",buffer);
Bugs
The man pages lists the following about sprintf
Because sprintf() and vsprintf() assume an arbitrarily long string,callers must be careful not to overflow the actual space; this is often impossible to assure. Note that the length of the strings produced is locale-dependent and difficult to predict
Besides that, it is also vulnerable to Format String Vulnerabilities and hence proper checks must be put into place to prevent unwanted outcomes.
Conclusion
Hence, in this module,:
- Went over the definition of sprintf(..) function
- Discussed the type of arguments the function takes
- We even worked out an example
- Finally, we discussed some common bugs
That concludes our module on sprintf() function. Thank you for reading !