xref: /freebsd/lib/libc/stdio/printf.3 (revision 90aad5d3e44d137ce80d2ec257de07c7c1367bd3)
1.\" Copyright (c) 1990, 1991, 1993
2.\"	The Regents of the University of California.  All rights reserved.
3.\"
4.\" This code is derived from software contributed to Berkeley by
5.\" Chris Torek and the American National Standards Committee X3,
6.\" on Information Processing Systems.
7.\"
8.\" Redistribution and use in source and binary forms, with or without
9.\" modification, are permitted provided that the following conditions
10.\" are met:
11.\" 1. Redistributions of source code must retain the above copyright
12.\"    notice, this list of conditions and the following disclaimer.
13.\" 2. Redistributions in binary form must reproduce the above copyright
14.\"    notice, this list of conditions and the following disclaimer in the
15.\"    documentation and/or other materials provided with the distribution.
16.\" 3. Neither the name of the University nor the names of its contributors
17.\"    may be used to endorse or promote products derived from this software
18.\"    without specific prior written permission.
19.\"
20.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30.\" SUCH DAMAGE.
31.\"
32.\"     @(#)printf.3	8.1 (Berkeley) 6/4/93
33.\"
34.Dd May 22, 2018
35.Dt PRINTF 3
36.Os
37.Sh NAME
38.Nm printf ,
39.Nm fprintf ,
40.Nm sprintf ,
41.Nm snprintf ,
42.Nm asprintf ,
43.Nm dprintf ,
44.Nm vprintf ,
45.Nm vfprintf ,
46.Nm vsprintf ,
47.Nm vsnprintf ,
48.Nm vasprintf ,
49.Nm vdprintf
50.Nd formatted output conversion
51.Sh LIBRARY
52.Lb libc
53.Sh SYNOPSIS
54.In stdio.h
55.Ft int
56.Fn printf "const char * restrict format" ...
57.Ft int
58.Fn fprintf "FILE * restrict stream" "const char * restrict format" ...
59.Ft int
60.Fn sprintf "char * restrict str" "const char * restrict format" ...
61.Ft int
62.Fn snprintf "char * restrict str" "size_t size" "const char * restrict format" ...
63.Ft int
64.Fn asprintf "char **ret" "const char *format" ...
65.Ft int
66.Fn dprintf "int fd" "const char * restrict format" ...
67.In stdarg.h
68.Ft int
69.Fn vprintf "const char * restrict format" "va_list ap"
70.Ft int
71.Fn vfprintf "FILE * restrict stream" "const char * restrict format" "va_list ap"
72.Ft int
73.Fn vsprintf "char * restrict str" "const char * restrict format" "va_list ap"
74.Ft int
75.Fn vsnprintf "char * restrict str" "size_t size" "const char * restrict format" "va_list ap"
76.Ft int
77.Fn vasprintf "char **ret" "const char *format" "va_list ap"
78.Ft int
79.Fn vdprintf "int fd" "const char * restrict format" "va_list ap"
80.Sh DESCRIPTION
81The
82.Fn printf
83family of functions produces output according to a
84.Fa format
85as described below.
86The
87.Fn printf
88and
89.Fn vprintf
90functions
91write output to
92.Dv stdout ,
93the standard output stream;
94.Fn fprintf
95and
96.Fn vfprintf
97write output to the given output
98.Fa stream ;
99.Fn dprintf
100and
101.Fn vdprintf
102write output to the given file descriptor;
103.Fn sprintf ,
104.Fn snprintf ,
105.Fn vsprintf ,
106and
107.Fn vsnprintf
108write to the character string
109.Fa str ;
110and
111.Fn asprintf
112and
113.Fn vasprintf
114dynamically allocate a new string with
115.Xr malloc 3 .
116.Pp
117These functions write the output under the control of a
118.Fa format
119string that specifies how subsequent arguments
120(or arguments accessed via the variable-length argument facilities of
121.Xr stdarg 3 )
122are converted for output.
123.Pp
124The
125.Fn asprintf
126and
127.Fn vasprintf
128functions
129set
130.Fa *ret
131to be a pointer to a buffer sufficiently large to hold the formatted string.
132This pointer should be passed to
133.Xr free 3
134to release the allocated storage when it is no longer needed.
135If sufficient space cannot be allocated,
136.Fn asprintf
137and
138.Fn vasprintf
139will return \-1 and set
140.Fa ret
141to be a
142.Dv NULL
143pointer.
144.Pp
145The
146.Fn snprintf
147and
148.Fn vsnprintf
149functions
150will write at most
151.Fa size Ns \-1
152of the characters printed into the output string
153(the
154.Fa size Ns 'th
155character then gets the terminating
156.Ql \e0 ) ;
157if the return value is greater than or equal to the
158.Fa size
159argument, the string was too short
160and some of the printed characters were discarded.
161The output is always null-terminated, unless
162.Fa size
163is 0.
164.Pp
165The
166.Fn sprintf
167and
168.Fn vsprintf
169functions
170effectively assume a
171.Fa size
172of
173.Dv INT_MAX + 1.
174.Pp
175The format string is composed of zero or more directives:
176ordinary
177.\" multibyte
178characters (not
179.Cm % ) ,
180which are copied unchanged to the output stream;
181and conversion specifications, each of which results
182in fetching zero or more subsequent arguments.
183Each conversion specification is introduced by
184the
185.Cm %
186character.
187The arguments must correspond properly (after type promotion)
188with the conversion specifier.
189After the
190.Cm % ,
191the following appear in sequence:
192.Bl -bullet
193.It
194An optional field, consisting of a decimal digit string followed by a
195.Cm $ ,
196specifying the next argument to access.
197If this field is not provided, the argument following the last
198argument accessed will be used.
199Arguments are numbered starting at
200.Cm 1 .
201If unaccessed arguments in the format string are interspersed with ones that
202are accessed the results will be indeterminate.
203.It
204Zero or more of the following flags:
205.Bl -tag -width ".So \  Sc (space)"
206.It Sq Cm #
207The value should be converted to an
208.Dq alternate form .
209For
210.Cm c , d , i , n , p , s ,
211and
212.Cm u
213conversions, this option has no effect.
214For
215.Cm o
216conversions, the precision of the number is increased to force the first
217character of the output string to a zero.
218For
219.Cm x
220and
221.Cm X
222conversions, a non-zero result has the string
223.Ql 0x
224(or
225.Ql 0X
226for
227.Cm X
228conversions) prepended to it.
229For
230.Cm a , A , e , E , f , F , g ,
231and
232.Cm G
233conversions, the result will always contain a decimal point, even if no
234digits follow it (normally, a decimal point appears in the results of
235those conversions only if a digit follows).
236For
237.Cm g
238and
239.Cm G
240conversions, trailing zeros are not removed from the result as they
241would otherwise be.
242.It So Cm 0 Sc (zero)
243Zero padding.
244For all conversions except
245.Cm n ,
246the converted value is padded on the left with zeros rather than blanks.
247If a precision is given with a numeric conversion
248.Cm ( d , i , o , u , i , x ,
249and
250.Cm X ) ,
251the
252.Cm 0
253flag is ignored.
254.It Sq Cm \-
255A negative field width flag;
256the converted value is to be left adjusted on the field boundary.
257Except for
258.Cm n
259conversions, the converted value is padded on the right with blanks,
260rather than on the left with blanks or zeros.
261A
262.Cm \-
263overrides a
264.Cm 0
265if both are given.
266.It So "\ " Sc (space)
267A blank should be left before a positive number
268produced by a signed conversion
269.Cm ( a , A , d , e , E , f , F , g , G ,
270or
271.Cm i ) .
272.It Sq Cm +
273A sign must always be placed before a
274number produced by a signed conversion.
275A
276.Cm +
277overrides a space if both are used.
278.It So "'" Sc (apostrophe)
279Decimal conversions
280.Cm ( d , u ,
281or
282.Cm i )
283or the integral portion of a floating point conversion
284.Cm ( f
285or
286.Cm F )
287should be grouped and separated by thousands using
288the non-monetary separator returned by
289.Xr localeconv 3 .
290.El
291.It
292An optional decimal digit string specifying a minimum field width.
293If the converted value has fewer characters than the field width, it will
294be padded with spaces on the left (or right, if the left-adjustment
295flag has been given) to fill out
296the field width.
297.It
298An optional precision, in the form of a period
299.Cm \&.
300followed by an
301optional digit string.
302If the digit string is omitted, the precision is taken as zero.
303This gives the minimum number of digits to appear for
304.Cm d , i , o , u , x ,
305and
306.Cm X
307conversions, the number of digits to appear after the decimal-point for
308.Cm a , A , e , E , f ,
309and
310.Cm F
311conversions, the maximum number of significant digits for
312.Cm g
313and
314.Cm G
315conversions, or the maximum number of characters to be printed from a
316string for
317.Cm s
318conversions.
319.It
320An optional length modifier, that specifies the size of the argument.
321The following length modifiers are valid for the
322.Cm d , i , n , o , u , x ,
323or
324.Cm X
325conversion:
326.Bl -column ".Cm q Em (deprecated)" ".Vt signed char" ".Vt unsigned long long" ".Vt long long *"
327.It Sy Modifier Ta Cm d , i Ta Cm o , u , x , X Ta Cm n
328.It Cm hh Ta Vt "signed char" Ta Vt "unsigned char" Ta Vt "signed char *"
329.It Cm h Ta Vt short Ta Vt "unsigned short" Ta Vt "short *"
330.It Cm l No (ell) Ta Vt long Ta Vt "unsigned long" Ta Vt "long *"
331.It Cm ll No (ell ell) Ta Vt "long long" Ta Vt "unsigned long long" Ta Vt "long long *"
332.It Cm j Ta Vt intmax_t Ta Vt uintmax_t Ta Vt "intmax_t *"
333.It Cm t Ta Vt ptrdiff_t Ta (see note) Ta Vt "ptrdiff_t *"
334.It Cm z Ta (see note) Ta Vt size_t Ta (see note)
335.It Cm q Em (deprecated) Ta Vt quad_t Ta Vt u_quad_t Ta Vt "quad_t *"
336.El
337.Pp
338Note:
339the
340.Cm t
341modifier, when applied to a
342.Cm o , u , x ,
343or
344.Cm X
345conversion, indicates that the argument is of an unsigned type
346equivalent in size to a
347.Vt ptrdiff_t .
348The
349.Cm z
350modifier, when applied to a
351.Cm d
352or
353.Cm i
354conversion, indicates that the argument is of a signed type equivalent in
355size to a
356.Vt size_t .
357Similarly, when applied to an
358.Cm n
359conversion, it indicates that the argument is a pointer to a signed type
360equivalent in size to a
361.Vt size_t .
362.Pp
363The following length modifier is valid for the
364.Cm a , A , e , E , f , F , g ,
365or
366.Cm G
367conversion:
368.Bl -column ".Sy Modifier" ".Cm a , A , e , E , f , F , g , G"
369.It Sy Modifier Ta Cm a , A , e , E , f , F , g , G
370.It Cm l No (ell) Ta Vt double
371(ignored, same behavior as without it)
372.It Cm L Ta Vt "long double"
373.El
374.Pp
375The following length modifier is valid for the
376.Cm c
377or
378.Cm s
379conversion:
380.Bl -column ".Sy Modifier" ".Vt wint_t" ".Vt wchar_t *"
381.It Sy Modifier Ta Cm c Ta Cm s
382.It Cm l No (ell) Ta Vt wint_t Ta Vt "wchar_t *"
383.El
384.It
385A character that specifies the type of conversion to be applied.
386.El
387.Pp
388A field width or precision, or both, may be indicated by
389an asterisk
390.Ql *
391or an asterisk followed by one or more decimal digits and a
392.Ql $
393instead of a
394digit string.
395In this case, an
396.Vt int
397argument supplies the field width or precision.
398A negative field width is treated as a left adjustment flag followed by a
399positive field width; a negative precision is treated as though it were
400missing.
401If a single format directive mixes positional
402.Pq Li nn$
403and non-positional arguments, the results are undefined.
404.Pp
405The conversion specifiers and their meanings are:
406.Bl -tag -width ".Cm diouxX"
407.It Cm diouxX
408The
409.Vt int
410(or appropriate variant) argument is converted to signed decimal
411.Cm ( d
412and
413.Cm i ) ,
414unsigned octal
415.Pq Cm o ,
416unsigned decimal
417.Pq Cm u ,
418or unsigned hexadecimal
419.Cm ( x
420and
421.Cm X )
422notation.
423The letters
424.Dq Li abcdef
425are used for
426.Cm x
427conversions; the letters
428.Dq Li ABCDEF
429are used for
430.Cm X
431conversions.
432The precision, if any, gives the minimum number of digits that must
433appear; if the converted value requires fewer digits, it is padded on
434the left with zeros.
435.It Cm DOU
436The
437.Vt "long int"
438argument is converted to signed decimal, unsigned octal, or unsigned
439decimal, as if the format had been
440.Cm ld , lo ,
441or
442.Cm lu
443respectively.
444These conversion characters are deprecated, and will eventually disappear.
445.It Cm eE
446The
447.Vt double
448argument is rounded and converted in the style
449.Sm off
450.Oo \- Oc Ar d Li \&. Ar ddd Li e \(+- Ar dd
451.Sm on
452where there is one digit before the
453decimal-point character
454and the number of digits after it is equal to the precision;
455if the precision is missing,
456it is taken as 6; if the precision is
457zero, no decimal-point character appears.
458An
459.Cm E
460conversion uses the letter
461.Ql E
462(rather than
463.Ql e )
464to introduce the exponent.
465The exponent always contains at least two digits; if the value is zero,
466the exponent is 00.
467.Pp
468For
469.Cm a , A , e , E , f , F , g ,
470and
471.Cm G
472conversions, positive and negative infinity are represented as
473.Li inf
474and
475.Li -inf
476respectively when using the lowercase conversion character, and
477.Li INF
478and
479.Li -INF
480respectively when using the uppercase conversion character.
481Similarly, NaN is represented as
482.Li nan
483when using the lowercase conversion, and
484.Li NAN
485when using the uppercase conversion.
486.It Cm fF
487The
488.Vt double
489argument is rounded and converted to decimal notation in the style
490.Sm off
491.Oo \- Oc Ar ddd Li \&. Ar ddd ,
492.Sm on
493where the number of digits after the decimal-point character
494is equal to the precision specification.
495If the precision is missing, it is taken as 6; if the precision is
496explicitly zero, no decimal-point character appears.
497If a decimal point appears, at least one digit appears before it.
498.It Cm gG
499The
500.Vt double
501argument is converted in style
502.Cm f
503or
504.Cm e
505(or
506.Cm F
507or
508.Cm E
509for
510.Cm G
511conversions).
512The precision specifies the number of significant digits.
513If the precision is missing, 6 digits are given; if the precision is zero,
514it is treated as 1.
515Style
516.Cm e
517is used if the exponent from its conversion is less than \-4 or greater than
518or equal to the precision.
519Trailing zeros are removed from the fractional part of the result; a
520decimal point appears only if it is followed by at least one digit.
521.It Cm aA
522The
523.Vt double
524argument is rounded and converted to hexadecimal notation in the style
525.Sm off
526.Oo \- Oc Li 0x Ar h Li \&. Ar hhhp Oo \(+- Oc Ar d ,
527.Sm on
528where the number of digits after the hexadecimal-point character
529is equal to the precision specification.
530If the precision is missing, it is taken as enough to represent
531the floating-point number exactly, and no rounding occurs.
532If the precision is zero, no hexadecimal-point character appears.
533The
534.Cm p
535is a literal character
536.Ql p ,
537and the exponent consists of a positive or negative sign
538followed by a decimal number representing an exponent of 2.
539The
540.Cm A
541conversion uses the prefix
542.Dq Li 0X
543(rather than
544.Dq Li 0x ) ,
545the letters
546.Dq Li ABCDEF
547(rather than
548.Dq Li abcdef )
549to represent the hex digits, and the letter
550.Ql P
551(rather than
552.Ql p )
553to separate the mantissa and exponent.
554.Pp
555Note that there may be multiple valid ways to represent floating-point
556numbers in this hexadecimal format.
557For example,
558.Li 0x1.92p+1 , 0x3.24p+0 , 0x6.48p-1 ,
559and
560.Li 0xc.9p-2
561are all equivalent.
562.Fx 8.0
563and later always prints finite non-zero numbers using
564.Ql 1
565as the digit before the hexadecimal point.
566Zeroes are always represented with a mantissa of 0 (preceded by a
567.Ql -
568if appropriate) and an exponent of
569.Li +0 .
570.It Cm C
571Treated as
572.Cm c
573with the
574.Cm l
575(ell) modifier.
576.It Cm c
577The
578.Vt int
579argument is converted to an
580.Vt "unsigned char" ,
581and the resulting character is written.
582.Pp
583If the
584.Cm l
585(ell) modifier is used, the
586.Vt wint_t
587argument shall be converted to a
588.Vt wchar_t ,
589and the (potentially multi-byte) sequence representing the
590single wide character is written, including any shift sequences.
591If a shift sequence is used, the shift state is also restored
592to the original state after the character.
593.It Cm S
594Treated as
595.Cm s
596with the
597.Cm l
598(ell) modifier.
599.It Cm s
600The
601.Vt "char *"
602argument is expected to be a pointer to an array of character type (pointer
603to a string).
604Characters from the array are written up to (but not including)
605a terminating
606.Dv NUL
607character;
608if a precision is specified, no more than the number specified are
609written.
610If a precision is given, no null character
611need be present; if the precision is not specified, or is greater than
612the size of the array, the array must contain a terminating
613.Dv NUL
614character.
615.Pp
616If the
617.Cm l
618(ell) modifier is used, the
619.Vt "wchar_t *"
620argument is expected to be a pointer to an array of wide characters
621(pointer to a wide string).
622For each wide character in the string, the (potentially multi-byte)
623sequence representing the
624wide character is written, including any shift sequences.
625If any shift sequence is used, the shift state is also restored
626to the original state after the string.
627Wide characters from the array are written up to (but not including)
628a terminating wide
629.Dv NUL
630character;
631if a precision is specified, no more than the number of bytes specified are
632written (including shift sequences).
633Partial characters are never written.
634If a precision is given, no null character
635need be present; if the precision is not specified, or is greater than
636the number of bytes required to render the multibyte representation of
637the string, the array must contain a terminating wide
638.Dv NUL
639character.
640.It Cm p
641The
642.Vt "void *"
643pointer argument is printed in hexadecimal (as if by
644.Ql %#x
645or
646.Ql %#lx ) .
647.It Cm n
648The number of characters written so far is stored into the
649integer indicated by the
650.Vt "int *"
651(or variant) pointer argument.
652No argument is converted.
653.It Cm m
654Print the string representation of the error code stored in the
655.Dv errno
656variable at the beginning of the call, as returned by
657.Xr strerror 3 .
658No argument is taken.
659.It Cm %
660A
661.Ql %
662is written.
663No argument is converted.
664The complete conversion specification
665is
666.Ql %% .
667.El
668.Pp
669The decimal point
670character is defined in the program's locale (category
671.Dv LC_NUMERIC ) .
672.Pp
673In no case does a non-existent or small field width cause truncation of
674a numeric field; if the result of a conversion is wider than the field
675width, the
676field is expanded to contain the conversion result.
677.Sh RETURN VALUES
678These functions return the number of characters printed
679(not including the trailing
680.Ql \e0
681used to end output to strings),
682except for
683.Fn snprintf
684and
685.Fn vsnprintf ,
686which return the number of characters that would have been printed if the
687.Fa size
688were unlimited
689(again, not including the final
690.Ql \e0 ) .
691These functions return a negative value if an error occurs.
692.Sh EXAMPLES
693To print a date and time in the form
694.Dq Li "Sunday, July 3, 10:02" ,
695where
696.Fa weekday
697and
698.Fa month
699are pointers to strings:
700.Bd -literal -offset indent
701#include <stdio.h>
702fprintf(stdout, "%s, %s %d, %.2d:%.2d\en",
703	weekday, month, day, hour, min);
704.Ed
705.Pp
706To print \*(Pi
707to five decimal places:
708.Bd -literal -offset indent
709#include <math.h>
710#include <stdio.h>
711fprintf(stdout, "pi = %.5f\en", 4 * atan(1.0));
712.Ed
713.Pp
714To allocate a 128 byte string and print into it:
715.Bd -literal -offset indent
716#include <stdio.h>
717#include <stdlib.h>
718#include <stdarg.h>
719char *newfmt(const char *fmt, ...)
720{
721	char *p;
722	va_list ap;
723	if ((p = malloc(128)) == NULL)
724		return (NULL);
725	va_start(ap, fmt);
726	(void) vsnprintf(p, 128, fmt, ap);
727	va_end(ap);
728	return (p);
729}
730.Ed
731.Sh COMPATIBILITY
732The conversion formats
733.Cm \&%D , \&%O ,
734and
735.Cm \&%U
736are not standard and
737are provided only for backward compatibility.
738The conversion format
739.Cm \&%m
740is also not standard and provides the popular extension from the
741.Tn GNU C
742library.
743.Pp
744The effect of padding the
745.Cm %p
746format with zeros (either by the
747.Cm 0
748flag or by specifying a precision), and the benign effect (i.e., none)
749of the
750.Cm #
751flag on
752.Cm %n
753and
754.Cm %p
755conversions, as well as other
756nonsensical combinations such as
757.Cm %Ld ,
758are not standard; such combinations
759should be avoided.
760.Sh ERRORS
761In addition to the errors documented for the
762.Xr write 2
763system call, the
764.Fn printf
765family of functions may fail if:
766.Bl -tag -width Er
767.It Bq Er EILSEQ
768An invalid wide character code was encountered.
769.It Bq Er ENOMEM
770Insufficient storage space is available.
771.It Bq Er EOVERFLOW
772The
773.Fa size
774argument exceeds
775.Dv INT_MAX + 1 ,
776or the return value would be too large to be represented by an
777.Vt int .
778.El
779.Sh SEE ALSO
780.Xr printf 1 ,
781.Xr errno 2 ,
782.Xr fmtcheck 3 ,
783.Xr scanf 3 ,
784.Xr setlocale 3 ,
785.Xr strerror 3 ,
786.Xr wprintf 3
787.Sh STANDARDS
788Subject to the caveats noted in the
789.Sx BUGS
790section below, the
791.Fn fprintf ,
792.Fn printf ,
793.Fn sprintf ,
794.Fn vprintf ,
795.Fn vfprintf ,
796and
797.Fn vsprintf
798functions
799conform to
800.St -ansiC
801and
802.St -isoC-99 .
803With the same reservation, the
804.Fn snprintf
805and
806.Fn vsnprintf
807functions conform to
808.St -isoC-99 ,
809while
810.Fn dprintf
811and
812.Fn vdprintf
813conform to
814.St -p1003.1-2008 .
815.Sh HISTORY
816The functions
817.Fn asprintf
818and
819.Fn vasprintf
820first appeared in the
821.Tn GNU C
822library.
823These were implemented by
824.An Peter Wemm Aq Mt peter@FreeBSD.org
825in
826.Fx 2.2 ,
827but were later replaced with a different implementation
828from
829.Ox 2.3
830by
831.An Todd C. Miller Aq Mt Todd.Miller@courtesan.com .
832The
833.Fn dprintf
834and
835.Fn vdprintf
836functions were added in
837.Fx 8.0 .
838The
839.Cm \&%m
840format extension first appeared in the
841.Tn GNU C
842library, and was implemented in
843.Fx 12.0 .
844.Sh BUGS
845The
846.Nm
847family of functions do not correctly handle multibyte characters in the
848.Fa format
849argument.
850.Sh SECURITY CONSIDERATIONS
851The
852.Fn sprintf
853and
854.Fn vsprintf
855functions are easily misused in a manner which enables malicious users
856to arbitrarily change a running program's functionality through
857a buffer overflow attack.
858Because
859.Fn sprintf
860and
861.Fn vsprintf
862assume an infinitely long string,
863callers must be careful not to overflow the actual space;
864this is often hard to assure.
865For safety, programmers should use the
866.Fn snprintf
867interface instead.
868For example:
869.Bd -literal
870void
871foo(const char *arbitrary_string, const char *and_another)
872{
873	char onstack[8];
874
875#ifdef BAD
876	/*
877	 * This first sprintf is bad behavior.  Do not use sprintf!
878	 */
879	sprintf(onstack, "%s, %s", arbitrary_string, and_another);
880#else
881	/*
882	 * The following two lines demonstrate better use of
883	 * snprintf().
884	 */
885	snprintf(onstack, sizeof(onstack), "%s, %s", arbitrary_string,
886	    and_another);
887#endif
888}
889.Ed
890.Pp
891The
892.Fn printf
893and
894.Fn sprintf
895family of functions are also easily misused in a manner
896allowing malicious users to arbitrarily change a running program's
897functionality by either causing the program
898to print potentially sensitive data
899.Dq "left on the stack" ,
900or causing it to generate a memory fault or bus error
901by dereferencing an invalid pointer.
902.Pp
903.Cm %n
904can be used to write arbitrary data to potentially carefully-selected
905addresses.
906Programmers are therefore strongly advised to never pass untrusted strings
907as the
908.Fa format
909argument, as an attacker can put format specifiers in the string
910to mangle your stack,
911leading to a possible security hole.
912This holds true even if the string was built using a function like
913.Fn snprintf ,
914as the resulting string may still contain user-supplied conversion specifiers
915for later interpolation by
916.Fn printf .
917.Pp
918Always use the proper secure idiom:
919.Pp
920.Dl "snprintf(buffer, sizeof(buffer), \*q%s\*q, string);"
921