我們要合併字符串的話,使用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