簡體   English   中英

訪問沖突錯誤-ucrtbased.dll

[英]Access violation error - ucrtbased.dll

ChatClient.exe中的0x0F4CD6F0(ucrtbased.dll)引發異常:0xC0000005:訪問沖突讀取位置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;
}

將Visual Studio 2017與默認的IDE調試工具一起使用。

input.append((char*)ch);

為什么要投射到指針? 那是非常錯誤的。 由於函數過載解析, std::string會嘗試從與該字符的強制ASCII值相對應的內存地址開始讀取C字符串,這不是您要使用的內存。 因此,訪問沖突……充其量。

您想要的是在相應的內存地址后面附加一個ASCII char而不是char*

當您使用它時,請使用適當的C ++強制轉換,它可能會對此錯誤,並且永遠不會讓您對其進行編譯。 再說一次,如果您有任何警告,即使是舊的C語言強制轉換也至少應該對此有所警告。

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

(注:我假設getch()不返回任何int不能安全地鑄造到char你的情況我並沒有考慮它的文檔,因為它似乎是有些老了。 conio愚蠢如果該值可能缺。范圍內,您有責任進行檢查,因為在導致溢出的情況下進行轉換最多會調用未定義的 不可靠/不可移植的行為。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM