Have you looked in <curses.h>
to see what the getch()
function does?
Hint: OSX and Linux are not the same as Windows.
Specifically, as a macro in <curses.h>
, we find:
#define getch() wgetch(stdscr)
Now, there appears, on your system, to be an actual function getch()
in the curses library, but it expects stdscr
to be set up, and that is done by the curses initialization functions (initscr()
and relatives), and that is signally not done by your code. So, your code is invoking undefined behaviour by calling curses routines before the correct initialization is done, leading to the crash.
(Good hint from dmckee - it helped get the link line out of acidzombie24, which was important.)
To get to a point where a single key-stroke can be read and the program terminated cleanly, you have to do a good deal of work on Unix (OSX, Linux). You would have to trap the initial state of the terminal, arrange for an atexit()
function - or some similar mechanism - to restore the state of the terminal, change the terminal from cooked mode into raw mode, then invoke a function to read a character (possibly just read(0, &c, 1)
), and do your exit. There might be other ways to do it - but it certainly will involve some setup and teardown operations.
One book that might help is "Advanced Unix Programming" by Mark Rochkind; it covers terminal handling at the level needed. Alternatively, you can use <curses.h>
properly - that will be simpler than a roll-your-own solution, and probably more reliable.