Search code examples
c++windowsdoublebuffereddouble-buffering

Why do random symbols appear when I do double buffering in console?


I am trying to use double buffering in console. I have written this code, it compiles, but in the created console few downmost lines are filled with random characters. ChangingCHAR_INFO cur[Width*Height]; into CHAR_INFO cur[Width*Height+200]; helps, but I don't understand why would memory of Width*Height be not enough for it.

#include <windows.h>
#include <ctime>

#define xMax 80
#define yMax 25
#define fPS 250
#define Delay 60

class dbconsole
{
private:
    int width, height, FPS, delay;
    HANDLE h0, h1;
    CHAR_INFO *chiBuffer;
    bool curBuffer;
    int drawingTimer;
public:
    dbconsole(int Width, int Height, int fps)
    {
        CHAR_INFO cur[Width*Height];
        width = Width;
        height = Height;
        FPS = fps;
        preparebuffer(h0);
        preparebuffer(h1);
        chiBuffer = cur;
        curBuffer = 0;
        drawingTimer = clock();
    }
    void preparebuffer(HANDLE &h)
    {
        CONSOLE_CURSOR_INFO cursor;
        cursor.bVisible = false;
        cursor.dwSize = 1;
        h = CreateConsoleScreenBuffer(
                GENERIC_READ | GENERIC_WRITE,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                NULL,
                CONSOLE_TEXTMODE_BUFFER,
                NULL);
        SetConsoleCursorInfo(h, &cursor);
    }
    void putpixel(int x, int y, CHAR_INFO input)
    {
        chiBuffer[x+width*y]=input;
    }
    void depict()
    {
        SMALL_RECT srctWriteRect;
        srctWriteRect.Top = 0;
        srctWriteRect.Left = 0;
        srctWriteRect.Bottom = yMax-1;
        srctWriteRect.Right = xMax-1;
        if ((clock()-drawingTimer)*FPS>CLOCKS_PER_SEC)
        {
            if (curBuffer)
            {
                WriteConsoleOutput(h0, chiBuffer, {xMax,yMax}, {0,0}, &srctWriteRect);
                SetConsoleActiveScreenBuffer(h0);
            }
            else
            {
                WriteConsoleOutput(h1, chiBuffer, {xMax,yMax}, {0,0}, &srctWriteRect);
                SetConsoleActiveScreenBuffer(h1);
            }
            curBuffer=!curBuffer;
            drawingTimer = clock();
        }
    }
};

int main(void)
{
    dbconsole myConsole = dbconsole(xMax,yMax,fPS);
    SetConsoleTitle("Use arrow keys to control character");
    long long movetimer = clock();
    int x = 0, y = 0;
    while (true)
    {
        for (int i = 0; i < xMax; i++) for (int j = 0; j < yMax; j++) myConsole.putpixel(i,j, {' ',16});
        if ((clock()-movetimer)*Delay>CLOCKS_PER_SEC)
        {
            if (GetAsyncKeyState(VK_RIGHT))
            {
                movetimer = clock();
                if (x < xMax-1) x++;
            }
            if (GetAsyncKeyState(VK_LEFT))
            {
                movetimer = clock();
                if (x > 0) x--;
            }
            if (GetAsyncKeyState(VK_DOWN))
            {
                movetimer = clock();
                if (y < yMax-1) y++;
            }
            if (GetAsyncKeyState(VK_UP))
            {
                movetimer = clock();
                if (y > 0) y--;
            }
            if (GetAsyncKeyState(VK_ESCAPE)) return 0;
        }
        myConsole.putpixel(x,y,{1,15|16});
        myConsole.depict();
    }
}

I think that the problem is due to the fact that some memory corresponding to chiBuffer is not reserved for it, but I don't get why. So, what is the problem?


Solution

  • Here:

    dbconsole(int Width, int Height, int fps)
    {
        CHAR_INFO cur[Width*Height];
        ....
        chiBuffer = cur;
    

    cur is a local variable, and once the constructor is left, it no longer exists. At this point, chiBuffer ceases to be a valid pointer, and any use of it causes undefined behavior.

    A simple solution would be to make chiBuffer a std::vector:

    // also: #include <vector> at the top
    std::vector<CHAR_INFO> chiBuffer;
    

    and initialize it in the constructor like so:

    dbconsole(int Width, int Height, int fps)
      : chiBuffer(Width * Height)
    {
      // cur no longer necessary.
    

    The only additional change this requires is

    //                     v----------v--- here
    WriteConsoleOutput(h0, &chiBuffer[0], {xMax,yMax}, {0,0}, &srctWriteRect);
    

    to extract a pointer from the vector that the C function WriteConsoleOutput can understand. This works because std::vector guarantees that it stores its elements contiguously in memory (like an array).