为什么错误的缓冲区内存分配只会在 Release 模式下编译时导致崩溃,而在 Debug 模式下不会?

Why would an incorrect memory allocation to a buffer only cause crashes when compiled in Release mode and not in Debug mode?

这是我成功完成的第一个项目,所以我有点不确定如何引用可执行文件与正在“调试模式”下处理和调试的项目,或者是否有多种方法可以这样做等等等等

但是,更具体地说,我遇到了一个堆损坏问题,该问题仅在 Visual Studio 2019 设置为发布模式时发生,吐出我程序的“exe”版本,然后通过它以这种形式的第一个调试会话。事实证明(我可能错了,但这是我在问题完全消失之前所做的最后一件事)以下代码:

std::unique_ptr<std::vector<Stat>> getSelStudStats(HWND listboxcharnames) {
    std::unique_ptr<std::vector<Stat>> selStats = std::make_unique<std::vector<Stat>>();
    int pos = ListBox_GetCurSel(listboxcharnames);
    int len = ListBox_GetTextLen(listboxcharnames, pos);
    const wchar_t* buffer = new const wchar_t[++len];
    ListBox_GetText(listboxcharnames, pos, buffer);

    for (int i = 0; i < getSize(); i++) {
        Character character = getCharacterPtr(i);

        std::wstring name = character.getName();
        if (name.compare(buffer) == 0) {
            *selStats = character.getAllStats();
            return selStats;
        }
    }
    return selStats;
    delete[] buffer;
}

未通过 len 将正确的大小分配给 buffer 变量。通过将前缀增量运算符添加到 len,现在可以考虑与列表框文本一起出现的空终止符;因此,堆损坏错误不再发生。

虽然我很高兴解决了这个问题,但我不知道为什么 VS2019 没有在调试模式下提出这个问题。在尝试调试问题时,我了解到发布模式下的优化可以更改代码执行的结构和顺序。

此代码块中是否有某些东西会造成我遇到的错误,但仅限于 Release Mode/executable 形式?

已编辑:我删除了最初围绕 ++len 的星号,以突出显示我引用的更改。对它造成的混乱表示歉意,这是可以理解的。

Docs 解释行为:

When you request a memory block, the debug heap manager allocates from the base heap a slightly larger block of memory than requested and returns a pointer to your portion of that block. For example, suppose your application contains the call: malloc( 10 ). In a Release build, malloc would call the base heap allocation routine requesting an allocation of 10 bytes. In a Debug build, however, malloc would call _malloc_dbg, which would then call the base heap allocation routine requesting an allocation of 10 bytes plus approximately 36 bytes of additional memory.

所以在调试中你不会溢出你的缓冲区。但是,它可能会在以后导致其他错误(但不太可能发生一个字节溢出。)