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