What's the Difference Between Printf and Printf_S in C?

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

printf() printf_s()

0

1 Answer

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
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest