c++ - strcpy_s 之后的 strcat_s 给出错误

标签 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 说应用程序在显示后触发了断点:

Expression: (L"String is not null terminated" && 0)

我试过了,还是不行。我发现的最接近的现有问题是 here .按照规定,手动将最后一个字符设置为 null 也无济于事。

有什么想法吗?

最佳答案

strlen(hello) 是错误的字符串长度,当时它完全是垃圾,因为 hello 甚至还没有初始化。

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

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

关于c++ - strcpy_s 之后的 strcat_s 给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49649645/

相关文章:

c++ - 使用 C++ 在其名称周围使用括号调用函数

c++ - 带字符串或字符的动态分配(数组)

c++ - 如何终止 C++ 中的 std::string?

c++ - 非 POD 类类型的聚合初始化?

c++ - 为什么我调用 D2D1::RenderTarget::DrawText() 导致重复发送 WM_PAINT?

c++ - 如何安装ConvNet库?

c++ - -1、+1 的所有组合的 vector 的 vector

c++ - 为什么有人会用 float 乘法而不是除法

c++ - 我如何在 C++11 中解决 SICP 2.4

c++ - 如何克服以下关于 std::vector<bool> 的错误?