C++ strcpy_s复制到新的字符数组时引发错误
C++ strcpy_s throws error when copying to new char array
我的目标是生成一个具有正确点数的新数组,并将旧字符数组复制到其中。
使用 strcpy_s 时,会引发异常。我无法弄清楚为什么会抛出异常,指出缓冲区太小。我不能使用向量或字符串。如何使用 strcpy_s 和字符数组解决此问题?
char str[4] = { 't', 'e', 's', 't' };
int allocated = 4;
char * reservedString = new char[allocated]();
strcpy_s(reservedString, allocated, str);
编辑:更改我的代码以将一个添加到数组中会给我同样的"缓冲区太小"异常。
char str[4] = { 't', 'e', 's', 't' };
int allocated = 4;
char * reservedString = new char[allocated+1]();
strcpy_s(reservedString, allocated, str);
编辑2:正如有人评论的那样,str 的大小需要设置为 5 并包含一个空终止符。谢谢你,这解决了我的问题。
更新的代码:
char str[5] = { 't', 'e', 's', 't', ' '};
int allocated = 5;
char * reservedString = new char[allocated]();
strcpy_s(reservedString, allocated, str);
您需要五个字符来存储以零结尾的字符串"test"
。您的str
数组只有四个字符,没有零终止符。如果你想要一个零终止符,请像这样声明它:
char str[] = "test";
那你当然需要
int allocated = 5;
之后:
char * reservedString = new char[allocated];
strcpy_s(reservedString, allocated, str);
char str[4] = { 't', 'e', 's', 't' };
是内存中的4字节数组。它不是一个字符串,它是完全随机的,在这 4 个字节之后会出现一个"尾随"零,以及介于两者之间的任意数量的其他数据。
但是,strcpy_s()
期望复制以零结尾的字符串,但它所做的额外功能之一是检查源字符串是否适合目标。它不会,这就是您收到错误的原因。
[...] 在运行时检测到以下错误,并调用当前安装的约束处理程序函数:
* src 或 dest 是一个空指针
* destsz 为零或大于 RSIZE_MAX
* destsz 小于或等于 strnlen_s(src, destsz(;换句话说,会发生
截断 * 源字符串和目标字符串之间会发生重叠
你得到第三个,会发生"垃圾"字节的截断。
-
str
不是字符串。字符串是非 NUL 字符的序列,以 NUL 结尾。 -
您应该将缓冲区的大小传递给
strcpy_s()
,而不是最大字符串大小(少一个(。 -
也就是说,如果您应该使用
strcpy_s()
。你不应该。使用
strcpy()
,或者您已经有确切的大小、memcpy()
或std::copy_n()
。 -
作为旁注,将内存归零只是为了转身并覆盖它是一种毫无意义的浪费。
您没有分配正确的内存:
char str[4] = { 't', 'e', 's', 't' };
它分配 5 个字节,每个字符 4 个,加上空终止符---
做:
char str[4] = { 't', 'e', 's', 't' };
char * reservedString = new char[5]();
strcpy_s(reservedString, allocated, str);
或:
char str[4] = { 't', 'e', 's', 't' };
char * reservedString = new char[5]();
strcpy(reservedString, str);
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 按字符值访问int数组
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- C++ 带结构的数组字符
- 数组字符包含量超出预期
- 读取文件并添加到数组字符
- 如何在Qt中更改或替换数组字符
- 为什么编译器不在参数中传递数组字符 *arr[] 的大小?
- 井字棋数组字符错误
- 分割数组字符