看到大家在代码中有很多用wcscpy、strcpy等的,这里总结下给大家参考下,希望对大家有帮助(这里的API都是windows平台下的,linux下的应该也有类似的替换函数):
_tcscpy、_tcscpy_s 都是不安全的,换成_tcsncpy /_tcsncpy_s好些,最好用_tcsncpy_s
wcscpy、wcscpy_s都是不安全的,换成wcsncpy / wcsncpy_s好些,最好用wcsncpy_s
非unicode 函数类似,linux版本类似。
下面是一些会导致出错的代码,直接都可以运行的,有兴趣的可以试试。
#define PARRAYSIZE(array) ((sizeof(array)/sizeof(array[0])))
void CWindowsApiTest::testwcscpy()
{
WCHAR strBuf1[] = L"你是一个好人!你是一个好人!";
WCHAR strBuf2[10] = {0};
wcscpy(strBuf2, strBuf1);
int iStrLen = wcslen(strBuf2);
bool bResult = (iStrLen <= 10);
CPPUNIT_ASSERT_EQUAL_MESSAGE("内存越界了!iStrLen变成14了.", bResult, true);
}
void CWindowsApiTest::testwcscpy_s()
{
WCHAR strBuf1[] = L"你是一个好人!你是一个好人!";
WCHAR strBuf2[10] = {0};
wcscpy_s(strBuf2, 10, strBuf1);
int iStrLen = wcslen(strBuf2);
bool bResult = (iStrLen <= 10);
CPPUNIT_ASSERT_EQUAL_MESSAGE("内存越界了!但是Debug版本会提示用户越界", bResult, true);
}
void CWindowsApiTest::testwcsncpy()
{
WCHAR strBuf1[] = L"你是一个好人!你是一个好人!";
WCHAR strBuf2[10] = {0};
wcsncpy(strBuf2, strBuf1, PARRAYSIZE(strBuf2));
int iStrLen = wcslen(strBuf2);
bool bResult = (iStrLen <= 10);
CPPUNIT_ASSERT_EQUAL_MESSAGE("内存越界了!没有地方放置结束符,iStrLen:28,正确用法:wcsncpy(strBuf2, strBuf1, PARRAYSIZE(strBuf2)-1);", bResult, true);
}
void CWindowsApiTest::testwcsncpy_s()
{
WCHAR strBuf1[] = L"你是一个好人!你是一个好人!";
WCHAR strBuf2[10] = {0};
wcsncpy_s(strBuf2, PARRAYSIZE(strBuf2), strBuf1, PARRAYSIZE(strBuf2) );
int iStrLen = wcslen(strBuf2);
bool bResult = (iStrLen <= 10);
CPPUNIT_ASSERT_EQUAL_MESSAGE("内存越界了!正确用法:wcsncpy_s(strBuf2, PARRAYSIZE(strBuf2), strBuf1, PARRAYSIZE(strBuf2) - 1);", bResult, true);
}