2.5 安全字符串函数
不安全的字符串函数 |
Strsafe函数 |
Safe CRT函数 (C运行库) |
strcpy, wcscpy, _tcscpy, _mbscpy, strcpy , lstrcpy, _tccpy, _mbccpy |
StringCchCopy StringCbCopy StringCchCopyEx StringCbCopyEx |
strcpy_s |
strcat, wcscat , _mbscat, strcat, lstrcat, , strcatbuff, strcatchain, _tccat, _mbccat |
StringCchCat StringCbCat StringCchCatEx StringCbCatEx |
strcat_s |
wnsprintf, wsprintf, sprintf, swprintf, _stprintf |
StringCchPrintf StringCbPrintf StringCchPrintfEx StringCbPrintfEx |
_snprintf_s _snwprintf_s |
目标缓冲区太小时,不发生截断 |
目标缓冲区太小时,会发生截断 |
不发生截断 |
★String Safe函数:微软提供的内联形式函数,可以当做API(在strsafe.h文件中,注意要在包含其他文件之后,才包含该文件!)
★Safe CRT函数:C运行库
【SafeString程序】自定义错误处理函数
/*--------------------------------------------------------------------------------------- 功能:实现课本P19页,自定义函数调用失败处理程序 ----------------------------------------------------------------------------------------*/ #include <tchar.h> #include <stdlib.h> #include <windows.h> #include <stdint.h> #include <crtdbg.h> //要用到_CrtSetReportMode函数 #include <strsafe.h> //自定义函数调用失败的处理程序——只有在Debug版下才有效,Release中所有的参数将被传入NULL或0。 //当某个函数调用失败,系统会调用该函数,同时传入“错误描述文本”、出错的函数名称,文件名及出错所在行数。 void InvalidParameterHandle(PCTSTR expression, PCTSTR function, PCTSTR file, unsigned int line, uintptr_t /*pReserved*/) { _tprintf(_T("expression %s, function %s, file %s, line %d "),expression,function,file,line); } int _tmain() { _CrtSetReportMode(_CRT_ASSERT, 0); //禁用“调试断言失败”对话框 TCHAR szBefore[5] = { _T('B'), _T('B'), _T('B'), _T('B') ,'