Ncurses / C / C ++: Using getstr () and preventing overflow (should be the best way to do this)

I am currently jumping into my first full C ++ project and am having problems with Ncurses.

getstr () requires a char array, but it is not possible to prevent buffer overflows. Let's pretend to use this input to get a name. Then my code will be as follows:

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 is not working. Is there a way to fix this fatal flaw in the program besides creating huge char arrays? Thank.

Note. I am using Ubuntu 12.04 with g ++

+3
source share
4 answers

:

int getnstr(char *str, int n);

n .

+6

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

7,3. getstr()
... , , getch() , end-of-file ....

, , getch() , char .

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

getch ? , , :

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

. ( ).

+1

On Windows, you can dynamically allocate a 50 MB buffer. This will ensure that the buffer does not overflow until the next patch on Tuesday, after which your box will be restarted again :)

0
source

All Articles