c++ - 访问冲突错误 - ucrtbased.dll

标签 c++ access-violation

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

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

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

使用带有默认 IDE 调试工具的 Visual Studio 2017。

最佳答案

input.append((char*)ch);

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

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

当您使用它时,请使用正确的 C++ 强制转换,这会在这个上出错并且永远不会让您编译它。话又说回来,如果你有任何警告,即使是旧的 C Actor 也应该至少警告过这一点。

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

(注意:我假设 getch() 不会返回任何不能安全转换为 charint。我没有查看它的文档,因为它似乎是一些旧的 conio 愚蠢。如果该值可能超出范围,则您有责任检查它,因为在导致溢出时进行转换会调用 undefined unreliable/non-portable 最好的行为。)

关于c++ - 访问冲突错误 - ucrtbased.dll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49882851/

相关文章:

c++ - 在 IMMDeviceEnumerator 上调用 SAFE_RELEASE 时崩溃

windows - 更改全景控件的背景会使Windows Phone 7.5中带有AccessViolationException的应用程序崩溃

c++ - CreateProcess 未处理的错误

c++ - OpenCV cvSaveImage Jpeg 压缩因子

c++ - 使用一维字符数组翻转图像

c++ - Winsock 应用程序中的线性航位推算

c++ - 使用 Dijkstra 的最大概率路径

c++ - libtool: install: error: 在安装之前用上面的命令重新链接 `libmyprog.la'

c# - 如何避免调用 CUDA Dll 的访问冲突异常?

windows - 帮助破译这个 fatal error (Java)