Ncurses/C/C++: Using getstr() and preventing overflow (There must be a better way to do this)

断了今生、忘了曾经 提交于 2019-12-07 12:08:18

问题


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++


回答1:


Use:

int getnstr(char *str, int n);

which reads at most n characters.




回答2:


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



回答3:


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).




回答4:


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 :)



来源:https://stackoverflow.com/questions/21735850/ncurses-c-c-using-getstr-and-preventing-overflow-there-must-be-a-better-wa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!