C++ strcpy_s复制到新的字符数组时引发错误

C++ strcpy_s throws error when copying to new char array

本文关键字:数组 字符 错误 strcpy 复制 C++      更新时间:2023-10-16

我的目标是生成一个具有正确点数的新数组,并将旧字符数组复制到其中。

使用 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(;换句话说,会发生
截断 * 源字符串和目标字符串之间会发生重叠

你得到第三个,会发生"垃圾"字节的截断。

  1. str不是字符串。字符串是非 NUL 字符的序列,以 NUL 结尾。

  2. 您应该将缓冲区的大小传递给strcpy_s(),而不是最大字符串大小(少一个(。

  3. 也就是说,如果您应该使用strcpy_s()你不应该。

    使用 strcpy() ,或者您已经有确切的大小、memcpy()std::copy_n()

  4. 作为旁注,将内存归零只是为了转身并覆盖它是一种毫无意义的浪费。

您没有分配正确的内存:

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);