Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

gets() function in C

I need help again! I thought it is pretty cool to use the gets() function because it is like the scanf() wherein I could get an input with whitespace. But I read in one of the threads (student info file handling) that it is not good to use because according to them, it is a devil's tool for creating buffer overflows (which I don't understand)

If I use the gets() function, I could do this. ENTER YOUR NAME: Keanu Reeves.

If I use the scanf(), I could only do this. ENTER YOUR NAME: Keanu

So I heed their advice and replaced all my gets() code with fgets(). The problem is now some of my codes are not working anymore...are there any functions other than gets() and fgets() which could read the whole line and which ignores the whitespace.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

it is a devil's tool for creating buffer overflows

Because gets does not take a length parameter, it doesn't know how large your input buffer is. If you pass in a 10-character buffer and the user enters 100 characters -- well, you get the point.

fgets is a safer alternative to gets because it takes the buffer length as a parameter, so you can call it like this:

fgets(str, 10, stdin);

and it will read in at most 9 characters.

the problem is now some of my codes are not working anymore

This is possibly because fgets also stores the final newline ( ) character in your buffer -- if your code is not expecting this, you should remove it manually:

int len = strlen(str);
if (len > 0 && str[len-1] == '
')
  str[len-1] = '';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...