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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章