fixed destructor

This commit is contained in:
Daniel Knuettel 2017-03-09 16:54:23 +01:00
parent b4d8720b93
commit 8f8ad4361f

22
main.c
View File

@ -52,14 +52,15 @@ static struct termios oldt, newt;
char * playfield; char * playfield;
char ** horizon; char ** horizon;
// break the mainloop, if there was a SIGINT
static volatile char sigint_received = 0; static volatile char sigint_received = 0;
static struct termios oldt, newt;
int main(void) int main(void)
{ {
// set up the terminal for our hacky game.... // set up the terminal for our hacky game....
static struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt); tcgetattr(STDIN_FILENO, &oldt);
newt = oldt; newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO); newt.c_lflag &= ~(ICANON | ECHO);
@ -84,6 +85,8 @@ int main(void)
playfield[pos] = ' '; playfield[pos] = ' ';
horizon[0][to_place] = ' '; horizon[0][to_place] = ' ';
// actually if...else produces
// smaller objectcode than switch
if(input == KEY_RIGHT) if(input == KEY_RIGHT)
{ {
pos++; pos++;
@ -108,11 +111,15 @@ int main(void)
print_horizon(horizon); print_horizon(horizon);
// set the player cursor
playfield[pos] = CHAR_ME; playfield[pos] = CHAR_ME;
// add the next enemy
to_place = (random() & 0xff) % WIDTH; to_place = (random() & 0xff) % WIDTH;
horizon[0][to_place] = CHAR_ENEMY; horizon[0][to_place] = CHAR_ENEMY;
put_line(playfield); put_line(playfield);
// player got hit.
if(horizon[LINES - 1][pos] == CHAR_ENEMY) if(horizon[LINES - 1][pos] == CHAR_ENEMY)
{ {
printf("GAME OVER!\nYour score was: %llu\n", score); printf("GAME OVER!\nYour score was: %llu\n", score);
@ -127,7 +134,7 @@ int main(void)
} }
if(score == 0) if(score == 0)
{ {
printf("Congrats. You won the game.\nAnd you have absolutely no life.\nat all.\n"); printf("Congrats. You won the game.\n");
break; break;
} }
@ -140,15 +147,20 @@ int main(void)
} }
input = get_last_key_or_default(); input = get_last_key_or_default();
} }
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return 0; return 0;
} }
// We need those signal handlers to
// free the memory properly.
// If they do not get caught the
// destructors will be skipped.
// should not happen.
void __attribute__((cold)) handle_sigint(int signum) void __attribute__((cold)) handle_sigint(int signum)
{ {
sigint_received = 1; sigint_received = 1;
} }
// should not happen.
void __attribute__((cold)) handle_sigterm(int signum) void __attribute__((cold)) handle_sigterm(int signum)
{ {
printf("\n\nTERMINATED!\n"); printf("\n\nTERMINATED!\n");
@ -172,6 +184,8 @@ void __attribute__((destructor)) clean(void)
{ {
free(playfield); free(playfield);
delete_horizon(horizon); delete_horizon(horizon);
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
printf("\n"); printf("\n");
} }