Reputation: 496
I have a function that is supposed to listen for input on a Windows console. It uses conio.h. It will get called about 20 times per second.
How can I prevent my memory getting clogged up? As far as I understand C, it will initialize a new char every time. I can't use a single common memory location. The function has to be completely self-encapsulated.
Is there an easier way to remove in
from memory after returning it, besides also returning its memory adress and calling free(*adress)
?
Code:
#include <conio.h>
// Passively listen for input, return char if input, else 0
char listen() {
char in = 0;
if (kbhit()) { // Some key was pressed
in = getch(); // Which key?
}
return in;
}
void forward(void);
// Usage, for instance control a figure in a game
void main(void) {
while (game) {
char input = listen()
if (input == 'w')
forward();
}
}
Upvotes: 1
Views: 72
Reputation: 134356
Is there an easier way to remove in from memory after returning it
You don't need to worry, for the variables with block scope and automatic storage duration, once the scope is over, their lifetime is also over and memory can be reclaimed automatically. As a programmer, you don't have to take any additional action.
That said, any half-decent compiler will optimize the code to something like the below to avoid the usage of any temporary variable, altogether.
char listen() {
if (kbhit()) { // Some key was pressed
return getch(); // Which key?
}
return 0;
}
That said, getch()
returns an int
, so you should better change the return type of the listen()
function to return an int
value, too.
Upvotes: 1