0

I was making a simple winapi coding and suddenly encountered a wierd problem. This code:

HANDLE hConsOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFOEX infoex;
GetConsoleScreenBufferInfoEx(hConsOut, &infoex);
cout << "x: " << infoex.dwCursorPosition.X;

gives me output of "x: -13108". while this:

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO info;
GetConsoleScreenBufferInfo(hConsole, &info);
cout << "x: " << info.dwCursorPosition.X;

gives me "x: 0", which is correct, expected answer.

I may be wrong, but isnt former an extended version of latter? And why, when having such similar uses, Extended version of buffer getting me (obviously) wrong data?

Both examples was taken from msdn and generates no compile-time errors.

First, i was interested in changing color of the console with

infoex.ColorTable[0] = RGB(255,0,0);
SetConsoleScreenBufferInfoEx(hConsOut, &infoex);

but when it failed, i decided to test if "infoex" variable got the right data. And it turned out that even retrieving cursor position with it was impossible.

Please tell me where am i wrong. Thanks in advance.

  • 3
    Many structures in the Windows API, such as `CONSOLE_SCREEN_BUFFER_INFOEX`, begin with a `cbSize` field that ***MUST*** be set to `sizeof (T)` before calling a function with that structure. – andlabs Apr 22 '16 at 12:27
  • 2
    More generally, you need to check every API call to see whether or not it was successful. Your code just *assumes* that the API call succeeded, so if it didn't, you're using uninitialized data. (The reason the call failed in this case is what andlabs said, you have to initialize `cbSize` yourself.) – Harry Johnston Apr 23 '16 at 01:25
  • @andlabs thanks! After your comment i made a deeper research of this structure and it realized, that i was using it wrong. Setting cbSize was the key. You can make is as an answer, I'll set it as a correct one. – Димон Черкашин Apr 24 '16 at 06:46
  • Checking for errors is the big take away lesson here – David Heffernan Apr 25 '16 at 06:32
  • 1
    -13108 = 0xCCCC which [indicates uninitialized memory access](https://stackoverflow.com/q/370195/995714), i.e. your call to `GetConsoleScreenBufferInfo` failed and didn't change the variable `info` – phuclv Aug 18 '18 at 11:39

1 Answers1

0

As stated above any call to GetConsoleScreenBufferInfoEx requires a valid cbSize value.

Here is a working code snip:

auto readHandle = GetStdHandle(STD_OUTPUT_HANDLE);
if (readHandle == INVALID_HANDLE_VALUE) {
    std::cerr << "! invalid handle\n";
}

CONSOLE_SCREEN_BUFFER_INFOEX info{0};
info.cbSize = sizeof(info);
if (GetConsoleScreenBufferInfoEx(readHandle, &info) == 0) {
    std::cerr << "! GetConsoleScreenBufferInfoEx failed\n";
}