Access violation error - ucrtbased.dll

0

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

I've been struggling to find the source of this error for days and I've finally isolated a snippet to illustrate the problem I'm having. The exception is thrown immediately after the switch statement. I have no idea what is causing this "access violation" in this relatively mundane piece of code you can see below:

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

Using Visual Studio 2017 with the default IDE debug tools.

c++
access-violation
asked on Stack Overflow Apr 17, 2018 by Lolechi

1 Answer

2
input.append((char*)ch);

Why are you casting to a pointer? That is extremely wrong. Due to function overload resolution, std::string will try to read a C string starting at the memory address corresponding to the cast ASCII value of that character... which is not your memory to use. Hence an access violation... at best.

What you want is to append an ASCII char, not a char* at the corresponding memory address.

While you're at it, use the proper C++ cast, which would have errored-out on this one and never let you compile it. Then again, if you had any warnings on, even the old C cast should've at least warned about this.

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

(N.B.: I assume getch() doesn't return any int that cannot be safely casted to char in your case. I didn't look into its docs as it seems to be some old conio silliness. If the value might be out of range, it's your responsibility to check that, as casting while causing overflow invokes undefined unreliable/non-portable behaviour at best.)

answered on Stack Overflow Apr 17, 2018 by underscore_d • edited Apr 17, 2018 by underscore_d

User contributions licensed under CC BY-SA 3.0