C++安全函数之strcat_s

来源:互联网 发布:遗传算法原理与应用 编辑:程序博客网 时间:2024/06/05 17:03

1.必须包含的头文件:<string.h>
2.函数申明:
errno_t strcat_s(   char *strDestination,   size_t numberOfElements,   const char *strSource );
3.参数介绍
strDestination
Null 终止的目标字符串缓冲区。
numberOfElements
目标字符串缓冲区的大小。
strSource
Null 终止的源字符串缓冲区。

strcat_s 功能追加 strSource 到 strDestination 并停止使用 null 字符的结果字符串。
strSource 的初始字符覆盖 strDestination终止 null 字符。
如果源和目标字符串重叠,则 strcat_s 的行为未定义。
注意第二个参数是缓冲区的总大小,而不是剩余的大小:

实际上:第二个参数是合并字符串后的字符数量。 即,源串大小 + 目标串大小 + 字符串结束符大小("\0")。

4.使用事例

<pre name="code" class="cpp"><pre name="code" class="cpp">#include "stdafx.h"  #include <stdlib.h> // malloc()  #include <string.h> // strcat_s() && strlen()  int _tmain(int argc, _TCHAR* argv[])  {  char *ret = (char*)malloc(120);  memset(ret, 0, sizeof(ret));  char *str1 = "This is a demonstration program, ";  char *str2 = "considerations for using strcat_s.";  int len1 = strlen(str1) + 1;  strcat_s(ret, len1, str1);  //strcat_s(ret, sizeof(ret), str1);      // Debug Assertion Failed  //strcat_s(ret, strlen(str1), str1);     // Program: ...  // File: .\tcscat_s.inl  // Line: 42  // Expression: (L"Buffer is too small" && 0)  strcat_s(ret, strlen(str1) + 1, str1);         int len2 = strlen(ret) + strlen(str2) + 1;         strcat_s(ret, len2, str2);         printf("%s", ret);  return 0;  }

5. 注意事项:
 在使用之前,要先对字符串初始化。
 更多注意事项,请参考:使用strcat_s注意事项


0 0
原创粉丝点击