// crt_snprintf_s.cpp
// compile with: /MTd
// These #defines enable secure template overloads
// (see last part of Examples() below)
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <crtdbg.h> // For _CrtSetReportMode
#include <errno.h>
// This example uses a 10-byte destination buffer.
int snprintf_s_tester( const char * fmt, int x, int count )
{
char dest[10];
printf( "\n" );
if ( count == _TRUNCATE )
printf( "%d-byte buffer; truncation semantics\n",
_countof(dest) );
else
printf( "count = %d; %d-byte buffer\n",
count, _countof(dest) );
int ret = _snprintf_s( dest, _countof(dest), count, fmt, x );
printf( " new contents of dest: '%s'\n", dest );
return ret;
}
void Examples()
{
// formatted output string is 9 characters long: "<<<123>>>"
snprintf_s_tester( "<<<%d>>>", 121, 8 );
snprintf_s_tester( "<<<%d>>>", 121, 9 );
snprintf_s_tester( "<<<%d>>>", 121, 10 );
printf( "\nDestination buffer too small:\n" );
snprintf_s_tester( "<<<%d>>>", 1221, 10 );
printf( "\nTruncation examples:\n" );
int ret = snprintf_s_tester( "<<<%d>>>", 1221, _TRUNCATE );
printf( " truncation %s occur\n", ret == -1 ? "did"
: "did not" );
ret = snprintf_s_tester( "<<<%d>>>", 121, _TRUNCATE );
printf( " truncation %s occur\n", ret == -1 ? "did"
: "did not" );
printf( "\nSecure template overload example:\n" );
char dest[10];
_snprintf( dest, 10, "<<<%d>>>", 12321 );
// With secure template overloads enabled (see #defines
// at top of file), the preceding line is replaced by
// _snprintf_s( dest, _countof(dest), 10, "<<<%d>>>", 12345 );
// Instead of causing a buffer overrun, _snprintf_s invokes
// the invalid parameter handler.
// If secure template overloads were disabled, _snprintf would
// write 10 characters and overrun the dest buffer.
printf( " new contents of dest: '%s'\n", dest );
}
void myInvalidParameterHandler(
const wchar_t* expression,
const wchar_t* function,
const wchar_t* file,
unsigned int line,
uintptr_t pReserved)
{
wprintf(L"Invalid parameter handler invoked: %s\n", expression);
}
int main( void )
{
_invalid_parameter_handler oldHandler, newHandler;
newHandler = myInvalidParameterHandler;
oldHandler = _set_invalid_parameter_handler(newHandler);
// Disable the message box for assertions.
_CrtSetReportMode(_CRT_ASSERT, 0);
Examples();
}