访问冲突错误 - ucrtbased.dll

Access violation error - ucrtbased.dll

Exception thrown at 0x0F4CD6F0 (ucrtbased.dll) in ChatClient.exe: 0xC0000005: Access violation reading location 0x00000068.

几天来我一直在努力寻找这个错误的根源,我终于分离出一个片段来说明我遇到的问题。在 switch 语句之后立即抛出异常。我不知道是什么导致了这段相对普通的代码 "access violation",您可以在下面看到:

#include <iostream>
#include <string>
#include <conio.h>

int main(){
    bool room = true, type = true;
    string input;
    unsigned int scroll = 0;
    while (room) {
        cout << input;
        /* Input */
        int ch = _getch();
        switch (ch) {
        case 72: /* scroll up */
            if (!type && scroll != sizeof(unsigned int))
                scroll++;
            break;
        case 80: /* scroll down */
            if (!type && scroll != 0)
                scroll--;
            break;
        case 13: /* Send message */
            input.clear();
            scroll = 0;
            break;
        case 27: // Quit loop
            room = false;
            break;
        case 9: // Switch between scrolling and typing modes
            if (type)
                type = false;
            else
                type = true;
            break;
        default:
            if (type && ch != -32) {
                input.append((char*)ch);
            }
            break;
        }
    } <- Exception thrown, probably when the while loop condition is re-evaluated?
    return 0;
}

使用 Visual Studio 2017 和默认 IDE 调试工具。

input.append((char*)ch);

为什么要转换为指针?那是极其错误的。由于函数重载解析,std::string 将尝试从与该字符的转换 ASCII 值相对应的内存地址开始读取 C 字符串...这不是您要使用的内存。因此访问冲突...充其量。

你想要的是在相应的内存地址附加一个 ASCII char,而不是 char*

当你在做的时候,使用正确的 C++ 转换,它会在这个上出错并且永远不会让你编译它。再一次,如果你有任何警告,即使是旧的 C 演员也应该至少警告过这个。

input.append( static_cast<char>(ch) );

(N.B.: 我假设 getch() 不会 return 任何 int 在你的情况下不能安全地转换为 char 。我没有查看它的文档,因为它似乎有些陈旧 conio 愚蠢。如果该值可能超出范围,则您有责任检查它,因为在导致溢出时进行转换会调用 undefined unreliable/non-portable 最好的行为。)