Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between printf and printf_s?

Tags:

c

printf

I just want to know the difference and I've already tried search on google.

  • printf()
  • printf_s()
like image 610
Eric Matheus Avatar asked Sep 07 '25 17:09

Eric Matheus


1 Answers

I learned something new today. I've never used the _s functions and always assumed they were vendor-supplied extensions, but they are actually defined in the language standard under Annex K, "Bounds-checking Interfaces". With respect to printf_s:

K.3.5.3.3 The printf_s function

Synopsis

1 #define _ _STDC_WANT_LIB_EXT1_ _ 1
  #include <stdio.h>
  int printf_s(const char * restrict format, ...);
Runtime-constraints

2 format shall not be a null pointer. The %n specifier394) (modified or not by flags, field width, or precision) shall not appear in the string pointed to by format. Any argument to printf_s corresponding to a %s specifier shall not be a null pointer.

3 If there is a runtime-constraint violation, the printf_s function does not attempt to produce further output, and it is unspecified to what extent printf_s produced output before discovering the runtime-constraint violation.

Description

4 The printf_s function is equivalent to the printf function except for the explicit runtime-constraints listed above.

Returns

5 The printf_s function returns the number of characters transmitted, or a negative value if an output error, encoding error, or runtime-constraint violation occurred.
394) It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed at by format when those characters are not a interpreted as a %n specifier. For example, if the entire format string was %%n.

C 2011 Online Draft

To summarize, printf_s performs additional runtime validation of its arguments not done by printf, and will not attempt to continue if any of those runtime validations fail.

The _s functions are optional, and the compiler is not required to support them. If they are supported, the macro __STDC_WANT_LIB_EXT1__ will be defined to 1, so if you want to use them you'll need to so something like

#if __STDC_WANT_LIB_EXT1__ == 1
    printf_s( "%s", "This is a test\n" );
#else
    printf( "%s", "This is a test\n" );
#endif
like image 93
John Bode Avatar answered Sep 09 '25 16:09

John Bode