Why does it call ReadConsole in a loop that distorts the stack?

I turned off line input with the following code:

DWORD dwConsoleMode;
GetConsoleMode(hStdIn, &dwConsoleMode);
dwConsoleMode ^= ENABLE_LINE_INPUT;
SetConsoleMode(hStdIn, dwConsoleMode);

Then I call ReadConsole in a loop ... in a loop:

wchar_t cBuf;

while (1) {
    /* Display Options */

    do {
        ReadConsole(hStdIn, &cBuf, 1, &dwNumRead, NULL);
    } while (!iswdigit(cBuf));

    putwchar(cBuf);

    if (cBuf == L'0') break;
}

If I run the program and immediately press 0, it will exist cleanly.
But if I press a bunch of keys, and then press 0 when the program exists, it will work with:

Runtime Check Error # 2 - cBuf variable stack is damaged.

Why does this damage the stack? The code is simple, so I canโ€™t understand whatโ€™s wrong.

A small program with which I can reproduce the problem with:

#include <windows.h>
#include <stdio.h>

int wmain(int argc, wchar_t *argv[])
{
    DWORD dwNumRead;
    wchar_t cBuf;

    HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);

    DWORD dwConsoleMode;
    GetConsoleMode(hStdIn, &dwConsoleMode);
    dwConsoleMode ^= ENABLE_LINE_INPUT;
    SetConsoleMode(hStdIn, dwConsoleMode);

    while (true)
    {
        wprintf(L"\nEnter option: ");

        do {
            ReadConsoleW(hStdIn, &cBuf, 1, &dwNumRead, NULL);
        } while (!iswdigit(cBuf));

        putwchar(cBuf);

        if (cBuf == L'0') break;
    }

    return 0;
}

After starting, you have to stretch your keyboard, and then press 0, and it will work with damage to the stack.

, .
Visual Studio 2010 .

+5
1

, Windows. , :

#include <windows.h>
#include <crtdbg.h>

int wmain(int argc, wchar_t *argv[])
{
    DWORD dwNumRead;
    wchar_t cBuf[2];

    cBuf[0] = cBuf[1] = 65535;

    HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
    SetConsoleMode(hStdIn, 0);

    while (true)
    {
        _ASSERT(ReadConsoleW(hStdIn, &cBuf[0], 1, &dwNumRead, NULL));
        _ASSERT(dwNumRead == 1);
        _ASSERT(cBuf[1] == 65535);
        Sleep(5000);
    }
}

, , , ReadConsoleW, .

cBuf[1] , , , ReadConsoleW .

: , . .

+7

All Articles