今天在微信公众号CPP开发者上看到了这篇文,特此与大家分享下。
1、gets()方法。
1 #include <stdio.h>
2 #include <string.h>
3
4 int main(void)
5 {
6 char buff[10];
7 memset(buff,0,sizeof(buff));
8
9 gets(buff);
10
11 printf("\n The buffer entered is [%s]\n",buff);
12
13 return 0;
14 }
man下对gets()的解释为:
gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with ‘\0’. No check for buffer overrun is performed (see BUGS below).
BUGS的解释及建议:
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
总结:
gets()会无上限的读取字符,使用时需确保足够的buff,否则容易溢出破坏程序,通常使用fgets代替。
2、strcpy()方法
1 #include <stdio.h>
2 #include <string.h>
3
4 int main(int argc,char *argv[])
5 {
6 int flag = 0;
7 char passwd[10];
8
9 memset(passwd,0,sizeof(passwd));
10
11 strcpy(passwd,argv[1]);
12
13 if(0 == strcmp("LinuxGeek",passwd))
14 {
15 flag = 1;
16 }
17
18 if(flag)
19 {
20 printf("\n Password cracked\n");
21 }
22 else
23 {
24 printf("\n Incorrect passwd\n");
25 }
26
27 return 0;
28 }
man下关于strcpy有个bug描述:
If the destination string of a strcpy() is not large enough, then any-thing might happen