C++安全函数之strcat_s


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注意事项


  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值