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