The code is here. When I run my program (I saved kbhit as a header file and kept it in my program folder), I get an uninitialized read access on the first instance of using kbhit (I am using DrMemory for memory debugging). I included sys/ioctl.h as my program wasn’t able to use FIONREAD without it. The thing that is having an issue is the call to tcsetattr(STDIN, TCSANOW, &term); I don’t fully understand how this works so any help would be appreciated. Thank you!
Edit: the exact message is “UNINITIALIZED READ: reading 12 bytes. system call ioctl.0x5402 parameter #2.” The line is from the tcsetattr() call. This error comes after saving kbhit as a cpp file and templating it in another file. The program runs just fine except for that one error.
Here is a version of the code which I modified to be actual C and not C++, since it was only being C++ out of carelessness with bool true/false and struct keywords.
And oh yeah, don't put this in a header file. Put it in a file called kbhit.c and delete or comment out the test main function. And in a header file just write the line:
Or you might need:
That's all you need in the header.
It looks correct to me and valgrind does not complain. I don't have Dr. Memory to check with.
How this code works is that it first uses
tcgetattrto read the termios (terminal input output settings, I think) struct. Then it modifies it by unsetting the ICANON bits. Canon is the canonical setting for terminals which includes line buffering. Then it writes the new termios values back to the terminal. withtcsetattr.The
ioctlcall gets how many bytes are waiting in the buffer. If there's bytes waiting, then someone pressed some kind of keys.