delete []触发断点

时间:2013-07-23 13:00:50

标签: c++ pointers triggers 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;
}

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

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

编辑:

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

1 个答案:

答案 0 :(得分: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;
}

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

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