当前位置:网站首页>strcpy_ S precautions for use. (do not use strcpy_s where memcpy_s can be used)

strcpy_ S precautions for use. (do not use strcpy_s where memcpy_s can be used)

2022-06-13 09:00:00 xiongpursuit88

strcpy_s() There are two versions of the function : Three parameter versions and two parameter versions , as follows :
When there are three parameters :
errno_t strcpy_s(
char *strDestination,
size_t numberOfElements,
const char *strSource
);
For two parameters :
errno_t strcpy_s(
char (&strDestination)[size],
const char *strSource
); // C++ only

The following focuses on three parameter versions .
Be sure to pay attention to : The second parameter numberOfElements It must be larger than the source space strSource Size . otherwise Debug The version will pop up ,release The version will crash .
such as
LPSTR l_pcDest = (char*)malloc(6);
char l_acPhyPosName[6] = { 0 };
sprintf_s(l_acPhyPosName, “HOP05”);
strcpy_s(l_pcDest, 6/ It can't be for 5, Must be greater than or equal to strlen(l_acPhyPosName)+1/, l_acPhyPosName);

however ,memcpy_s The second parameter in the needs to be greater than or equal to strlen(l_acPhyPosName).( Not greater than or equal to strlen(l_acPhyPosName)+1 Oh ) as follows :
LPSTR l_pcDest = (char*)malloc(6);
char l_acPhyPosName[6] = { 0 };
sprintf_s(l_acPhyPosName, “HOP03”);
memcpy_s(l_pcDest, 5/DestLen/, l_acPhyPosName, 5/SourceLen/);

// summary :strcpy_s And memcpy_s The difference between :
//strcpy_s Is a copy of the string , Source includes \0 Of , So the target length must be greater than or equal to strlen( Source )+1, and memcpy_s Memory considerations , As long as the target length is greater than or equal to the source length , Unwanted +1. 
// therefore , To avoid confusion , It works memcpy_s The place of , Don't use strcpy_s.
原网站

版权声明
本文为[xiongpursuit88]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270535254983.html