首页 > 其他 > 详细

使用strcat_s的注意事项

时间:2014-03-01 05:32:23      阅读:1500      评论:0      收藏:0      [点我收藏+]

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

    strcat_s函数声明:

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

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


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

bubuko.com,布布扣


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

        (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

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

bubuko.com,布布扣


    解决办法:

	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

使用strcat_s的注意事项,布布扣,bubuko.com

使用strcat_s的注意事项

原文:http://blog.csdn.net/xiaobin_hlj80/article/details/20136283

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!