Ncurses/C/C ++:使用getstr()并防止溢出(必须有更好的方法来执行此操作) [英] Ncurses/C/C++: Using getstr() and preventing overflow (There must be a better way to do this)
问题描述
我目前正在进入我的第一个完整的C ++项目,并且遇到了Ncurses的麻烦.
I am currently jumping into my first full C++ project and I've run into a hitch with Ncurses.
getstr()需要一个char数组作为输入,但是,没有办法防止缓冲区溢出.让我们假装我正在使用此输入来获取名称.我的代码如下:
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;
}
但是,如果用户决定使用160个以上的字符作为姓名,会发生什么?我收到错误消息,程序失败. 除了创建巨大的Char数组之外,是否有办法解决程序中的这种致命缺陷? 谢谢.
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.
注意:我正在使用带有g ++的Ubuntu 12.04
Note: I am using Ubuntu 12.04 with g++
推荐答案
使用:
int getnstr(char *str, int n);
最多读取n
个字符.
这篇关于Ncurses/C/C ++:使用getstr()并防止溢出(必须有更好的方法来执行此操作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!