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