使用strcat_s的注意事项

    我们要合并字符串的话,使用c语言编写的时候需要注意几点事项。

    strcat_s函数声明:

errno_t strcat_s(
   char *strDestination,
   size_t numberOfElements,
   const char *strSource 
);


    出现歧义的大部分为第2个参数。

 

    1. L"Buffer is too small" && 0

使用strcat_s的注意事项_第1张图片

 

当此参数被赋值为下面几种情况下,会发生。

(1)numberOfElements=sizeof(dst)

strcat_s(ret, sizeof(ret), str1);

(2)numberOfElements=strlen(src)

strcat_s(ret, strlen(str1), str1);


此错误提示我们目标(Buffer)过小。

实际上第二个参数是合并字符串后的字符数量。

 

即,源串大小 + 目标串大小 + 字符串结束符大小("\0")

       第(1)个错误只计算了目标串的大小.

       第(2)个错误只计算了源串的大小.

 

      2. L"String is not null terminated" && 0

          当我们没有初始化字符串的时候,就会出现。

使用strcat_s的注意事项_第2张图片

解决办法:

memset(ret, 0, sizeof(ret));

 

 

 

    此程序在VS2005+调试pass.

// strcatTest.cpp : Defines the entry point for the console application.
//

#include  // _tmain && _TCHAR
#include 

#include  // malloc()
#include  // strcat_s() && strlen()

int _tmain(int argc, _TCHAR* argv[])
{
	char *ret = (char*)malloc(128);
	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)      
    int len2 = strlen(ret) + strlen(str2) + 1;       
    strcat_s(ret, len2, str2);       
    printf("%s", ret);

    return 0;
}

 

参考文章:

    1. strcat_s --- MSDN

 

你可能感兴趣的:(Other)