strcpy_s之后的strcat_s给出错误

时间:2018-04-04 11:19:24

标签: c++

我正在尝试使用VS 2013在C ++中连接两个字符串。下面是代码:

char *stringOne = "Hello";
char *stringTwo = " There!"; 
char *hello = new char[strlen(stringOne) + strlen(stringTwo) + 1];
strcpy_s(hello, strlen(hello), stringOne);
//hello[strlen(stringOne)+1] = '\0';
strcat_s(hello, strlen(hello), stringTwo);//<-----Does not return from this call

如果strcat_s语句被注释,它运行正常,* hello包含“Hello”。

但有了它,VS说应用程序在显示后触发了断点:

  

表达式:( L“字符串不是空终止”&amp;&amp; 0)

无论如何我都没试过。我发现的最近的问题是here。按照规定,手动将最后一个字符设置为空也无济于事。

任何想法?

1 个答案:

答案 0 :(得分:1)

strlen(hello)是一个错误的字符串长度,分别是它当时的完全垃圾,因为hello甚至尚未初始化。

您用于分配目标缓冲区的表达式strlen(stringOne) + strlen(stringTwo) + 1将是适当的传递长度。

最好习惯检查_s函数的返回值,因为那样你就知道第一个函数调用已经失败了。