我正在尝试使用 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/