Secure CRT (hopefully fixed) code sample
Sorry for the confusion in the previous post. I guess it just shows again I’m no longer a full-time dev… As I had already changed the sample code, I left it the way it is now:
#include <stdio.h>
#include <stdlib.h> // _invalid_parameter_handler, _set_invalid_parameter_handler
#include <errno.h>
#include <iostream>
using namespace std ;
void myInvalidParameterHandler( const wchar_t * expression,
const wchar_t * function,
const wchar_t * file,
unsigned int line,
uintptr_t /* pReserved */ )
{
if ( expression && function && file )
{
wcout << L"Invalid parameter detected in function " << function
<< L". File: " << file << L" Line: " << line
<< endl
<< L"Expression: " << expression
<< endl ;
}
else
wcout << L"myInvalidParameterHandler got called."
<< endl ;
}
void main()
{
_set_invalid_parameter_handler( myInvalidParameterHandler ) ;
_CrtSetReportMode( _CRT_ASSERT, 0 ) ; // Disable the message box for assertions.
if ( -1 != printf( NULL ) || EINVAL != errno )
wcout << L"Unexpected printf() behaviour" << endl ;
wcout << L"----------" << endl ;
if ( 2 != printf( "%q\n" ) )
wcout << L"Unexpected printf() behaviour" << endl ;
wcout << L"----------" << endl ;
if ( -1 != printf_s( "%q\n" ) || EINVAL != errno ) // %q is not a valid format
wcout << L"Unexpected printf_s() behaviour" << endl ;
wcout << L"----------" << endl ;
wchar_t * fromBuffer = L"Maître Corbeau, sur un arbre perché, Tenait en son bec un fromage." ;
wchar_t toBuffer[10] ;
if ( ERANGE != wcscpy_s( toBuffer, sizeof(toBuffer) / sizeof(toBuffer[0]), fromBuffer ) )
wcout << L"Unexpected _tcscpy_s() behaviour" << endl ;
wcout << L"----------" << endl ;
}
In Debug mode, this outputs:
Invalid parameter detected in function printf. File: printf.c Line: 53
Expression: (format != ((void *)0))
----------
q
----------
Invalid parameter detected in function _output_s. File: f:\pd5\vctools\crt_bld\self_x86\crt\src\output.c Line: 872
Expression: (state != ST_INVALID)
----------
Invalid parameter detected in function wcscpy_s. File: wcscat_s.c Line: 116
Expression: ("Buffer too small", 0)
----------
In Release mode, I just realized that the myInvalidParameterHandler function does get called!
myInvalidParameterHandler got called.
----------
q
----------
myInvalidParameterHandler got called.
----------
myInvalidParameterHandler got called.
----------
Thank you readers!
Comments
- Anonymous
June 11, 2004
The doc actually says: "The parameters will all have the value NULL unless a debug version of the CRT library is used." - Anonymous
June 11, 2004
The comment has been removed