So I'm currently working on a project which uses ncurses
for output and input. In this program, the user should be able to, for example, write his name. The issue I'm having is with getnstr
, as it can cause some very weird and unexplainable segmentation faults. For example this code right here works fine as it is:
#include <ncurses.h>
#include <string>
int main()
{
char *word;
initscr();
WINDOW *window = newwin(100, 100, 0, 0);
nodelay(window, false);
refresh();
mvwgetnstr(window, 0, 0, word, 10);
mvwprintw(window, 0, 0, "Word written is %s", word);
wrefresh(window);
getch();
endwin();
}
However if I only add a single string variable inside of the main function for example in the form of this:
#include <ncurses.h>
#include <string>
int main()
{
std::string crashMe;
char *word;
initscr();
WINDOW *window = newwin(100, 100, 0, 0);
nodelay(window, false);
refresh();
mvwgetnstr(window, 0, 0, word, 10);
mvwprintw(window, 0, 0, "Word written is %s", word);
wrefresh(window);
getch();
endwin();
}
It will instead have a segmentation fault on the first keypress you are doing with getnstr
. I'm not sure if it's only on my computer or if I'm doing something horribly wrong with ncurses
but I find it weird that initializing a string variable is causing the issue. The same issue can be reproduced by introducing an additional char*
into the same brackets as the getnstr
.
If anyone has any thoughts about this issue, I'd greatly appreciate hearing them. Idk if it might be a C related thing causing my segmentation faults. Either way, thanks in advance.
You're asking to read 10 characters into a pointer that points nowhere in particular. Try either char word[10];
or char *word = malloc(10);
So why does that sometimes work? Your uninitialized pointer variable may have pointed to a writable memory area by accident. You were overwriting something somewhere, which may not always immediately crash.
I'm pretty sure that should have produced a compiler warning. Always compile with -Wall
and pay attention to the output.