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