【问题标题】:Why this delete[] action error?为什么这个 delete[] 操作错误?
【发布时间】:2016-01-19 01:39:14
【问题描述】:

我在使用后删除了一个 wchar_t 数组,但是失败了:

const wchar_t t1[] = L"A string";
const wchar_t* t2 = L"Other string";

wchar_t* w = new wchar_t[wcslen(t1) + wcslen(t2) + 1];

int len = swprintf_s(w, wcslen(w), L"%s%s", t1, t2);
w[len] = 0;

delete[] w;

我在delete[] w; 失败,出现错误write to the end of heap buffer,但我在Locals 检查w 是否正常:

如何解决这个错误?

【问题讨论】:

  • C 没有delete 运算符。将其重新标记为 C++。
  • 您可能在其他地方有 UB。按照如何提问中的指示,展示一个实际的测试用例。
  • swprintf_s(w, wcslen(w), ... w 最初是一个未初始化的缓冲区,因此在其上调用 wcslen 是不正确的。您想将缓冲区的 size 传递给swprintf_s
  • @JonathanPotter 你是对的。那是错误
  • 请勿发布文字图片。改为复制/粘贴文本!

标签: c++ arrays runtime-error heap-memory delete-operator


【解决方案1】:

已解决,正如@Jonathan Potter 指出的那样,错误是:

swprintf_s(w, wcslen(w), ... w 最初是一个未初始化的缓冲区,因此对其调用 wcslen 是不正确的。您想将缓冲区的大小传递给 swprintf_s

【讨论】:

    猜你喜欢
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    相关资源
    最近更新 更多