Question

I am currently jumping into my first full C++ project and I've run into a hitch with Ncurses.

getstr() requires a char array as input, but with this, there is no way to prevent buffer overflow. Lets pretend I'm using this input to get a name. My code would then be the following:

int main(){
    char* nameTemp = new char[160];
    initscr();
    getstr(nameTemp);
    endwin();
    delete nameTemp;
    return 0;
}

But what happens if the user decides to use more than 160 characters for his name? I get an error and the program fails. Is there a way to fix this kind of fatal flaw in the program besides creating huge Char arrays? Thanks.

Note: I am using Ubuntu 12.04 with g++

Was it helpful?

Solution

Use:

int getnstr(char *str, int n);

which reads at most n characters.

OTHER TIPS

From http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/scanw.html

7.3. getstr() class of functions
... In essence, this function performs the same task as would be achieved by a series of calls to getch() until a newline, carriage return, or end-of-file is received. ...

So, while it's not a perfect solution, you could just use getch() in a loop until you reach the end of the char array or until the user types a newline.

char* nameTemp = new char[160];
int i = 0;
// don't put anything in the last index, to ensure a properly ended string
while (i < 159) {
    nameTemp[i] = getch();
    if (nameTemp[i] == '\n') {
        break;
    } else if (nameTemp[i] == '\b') {
        nameTemp[i] = 0;
        i--;
        nameTemp[i] = 0;
        i--; // cancel out the increment at end of loop
    }
    i++;
}
nameTemp[i] = 0; // the \n or tempName[159], whichever comes first

How about using getch to get one character at a time? This way you have full control over what you are reading:

    std::string get_line()
    {
      std::string result;
      while(true)
      {
        int c = getch();
        if(c == ERR || c == '\n') return result;
        else result += c; 
      }
    }

For example. (This code is untested).

On Windows, you could dynamically-allocate a 50MB buffer. That will ensure that it is not realistically possible to overflow the buffer before the next Patch Tuesday, whereupon your box will get restarted anyway :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top