0

my goal is to get text from screen using ncurses in c++. To achieve this, I'm trying to use mvinstr() function, but I'm having problems with getting the arguments right - mostly the char *str. My guess is that it all comes down to my misuse of pointers, as I'm getting segmentation fault error. I'd really appreciate telling me what is wrong with my aproach here. Here is a link to a manpage: https://linux.die.net/man/3/winstr .

mvaddstr(1, 1, "text");

char *str;
mvinstr(1, 1, str); 

mvprintw(2, 1, str); //expected output: text
trommand
  • 21
  • 2

1 Answers1

0

The third parameter to mvinstr() is a pointer to a character buffer that's large enough for the string to be written to.

It is your repsonsibility to allocate the buffer and pass a valid character pointer. Since you did not allocate str to point to any buffer, this is undefined behavior. mvinstr() ends up writing through an initialized pointer, corrupting a random area of memory, resulting in a crash.

Since you know the width of the terminal screen, you can create a std::vector<char>, resize() it to be be big enough to accomodate the string (plus a trailing '\0' character), and pass a pointer to the first character in the std::vector to mvinstr(). Afterwards, you may wish to construct your std::string, from the character vector.

Alternatively, you can use a fixed size buffer of 1 character, and use mvinnstr() to extract one character at a time.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • Of what help exactly is knowing screen's size? Can't I just create vector that is already of string's size? What's the resize() step for? Here is code that I came up with following your instructions, but it still isn't quite working for me: `vector v; v.resize(5); mvinstr(1, 1, &v[0]);` – trommand Mar 02 '19 at 17:27
  • From the manual page: "These routines return a string of characters in str, extracted starting at the current cursor position in the named window." Without knowing the screen's size, how exactly do you propose to know how big your `char` buffer must be, in order to be big enough for the string? The only functions that will explicitly limit the number of characters extracted are the "n" functions. Otherwise the sky's the limit. Also, unfortunately "isn't quite working for me" is not a useful problem description. – Sam Varshavchik Mar 02 '19 at 17:37
  • Now I understand. Apologies for not being specific. Code above resulted in segfault for me, so I tried 'n' functions as you said and actually managed to get it working with: `char * str = new char[5];` and mvinnstr() function. – trommand Mar 02 '19 at 17:55