Secure CRT code sample
When built in debug mode with the Visual Studio 2005 Community Technology Preview May 2004, the following source code:
#include <stdio.h>
#include <stdlib.h> // _invalid_parameter_handler, _set_invalid_parameter_handler
#include <tchar.h>
#include <crtdbg.h>
#include <errno.h>
void myInvalidParameterHandler( const wchar_t * expression,
const wchar_t * function,
const wchar_t * file,
unsigned int line,
uintptr_t pReserved )
{
printf( _T("Invalid parameter detected in function %S. File: %S Line: %d\n"), function, file, line ) ;
printf( _T("Expression: %S\n\n"), expression ) ;
}
void _tmain()
{
_invalid_parameter_handler oldHandler = _set_invalid_parameter_handler( myInvalidParameterHandler ) ;
_CrtSetReportMode( _CRT_ASSERT, 0 ) ; // Disable the message box for assertions.
_ASSERTE( -1 == printf( NULL ) && EINVAL == errno ) ;
_ASSERTE( EINVAL == printf_s( NULL ) ) ;
TCHAR * fromBuffer = _T("Maître Corbeau, sur un arbre perché, Tenait en son bec un fromage." ) ;
TCHAR toBuffer[10] ;
// warning C4996: 'strcpy' was declared deprecated
// _tcscpy( toBuffer, fromBuffer ) ;
_ASSERTE( ERANGE == _tcscpy_s( toBuffer, sizeof(toBuffer) / sizeof(toBuffer[0]), fromBuffer ) ) ;
}
outputs:
Invalid parameter detected in function printf. File: printf.c Line: 53
Expression: (format != ((void *)0))
Invalid parameter detected in function vprintf_helper. File: vprintf.c Line: 51
Expression: (format != ((void *)0))
Invalid parameter detected in function strcpy_s. File: strcat_s.c Line: 112
Expression: ("Buffer too small", 0)
And in release mode, it outputs ... nothing.
Comments
- Anonymous
June 09, 2004
C++ assert macros only apply to debug mode...
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/crt__assert.2c._asserte_macros.asp - Anonymous
June 09, 2004
Good point Sean but mine was that myInvalidParameterHandler is not called in release mode. I should have been more specific. Thanks! - Anonymous
June 09, 2004
ah, so that's what you're getting at! ;) - Anonymous
June 10, 2004
The comment has been removed - Anonymous
June 10, 2004
Indeed! Sorry about that. And I realize that I did not understand Sean comment either which I'm sure was saying the same. Look for a follow-up post. Thanks guys!