delete []触发断点

Lpp*_*Edd 0 c++ triggers pointers breakpoints

这是我的示例代码:

int main()
{
    const wchar_t *envpath = L"hello\\";
    const wchar_t *dir = L"hello2\\";
    const wchar_t *core = L"hello3";

    wchar_t *corepath = new wchar_t[
        wcslen(envpath) +
        wcslen(dir) +
        wcslen(core)
    ];

    wcscpy_s(corepath, wcslen(corepath) + wcslen(envpath) + 1, envpath);
    wcscat_s(corepath, wcslen(corepath) + wcslen(dir) + 1, dir);
    wcscat_s(corepath, wcslen(corepath) + wcslen(core) + 1, core);

    delete []corepath;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

delete []corepath命令中,触发断点.
可能是什么原因?

如果我以这种方式重写代码:

    wcscpy_s(corepath, wcslen(envpath) + 1, envpath);
    wcscat_s(corepath, wcslen(corepath) + wcslen(dir) + 1, dir);
    wcscat_s(corepath, wcslen(corepath) + wcslen(core) + 1, core);
Run Code Online (Sandbox Code Playgroud)

删除指针时检测到堆损坏.

编辑:

我想我应该用corepath分配+1来存储结尾\ 0,对吗?

ava*_*kar 5

您没有分配足够的空间来包含终止零.最后一次调用wcscat_s将写入'\0'超出缓冲区末尾的指针corepath.

你也在wcscat_s谈论缓冲区的容量.容量是wcslen(envpath) + wcslen(dir) + wcslen(core),但你正在通过wcslen(corepath) + wcslen(core) + 1.

wcslen(corepath)corepath初始化之前你也在打电话.

固定代码应如下所示:

int main()
{
    const wchar_t *envpath = L"hello\\";
    const wchar_t *dir = L"hello2\\";
    const wchar_t *core = L"hello3";

    size_t cap = wcslen(envpath) +
        wcslen(dir) +
        wcslen(core) + 1;

    wchar_t *corepath = new wchar_t[cap];

    wcscpy_s(corepath, cap, envpath);
    wcscat_s(corepath, cap, dir);
    wcscat_s(corepath, cap, core);

    delete[] corepath;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

实际上,固定代码应如下所示:

#include <string>
int main()
{
    const wchar_t *envpath = L"hello\\";
    const wchar_t *dir = L"hello2\\";
    const wchar_t *core = L"hello3";

    std::wstring corepath = envpath;
    corepath.append(dir);
    corepath.append(core);
}
Run Code Online (Sandbox Code Playgroud)