使用strcat_s的注意事项

来源:互联网 发布:2017中国信贷规模数据 编辑:程序博客网 时间:2024/04/29 06:19

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

    strcat_s函数声明:

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

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


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



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

        (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

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



    解决办法:

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


    此演示程序在VS2005调试.

// strcatTest.cpp : Defines the entry point for the console application.//#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;}


    参考文章:

    1. strcat_s --- MSDN

3 0
原创粉丝点击