answersLogoWhite

0

gets is an insecure function, its careless use can lead to errors. If you

want to use gets, consider using fgets instead, supplying stdin as

the file reference parameter.

The gets function waits until a line of input is available (unless one is already

available), and consumes the whole line including the ENTER/newline at the end.

The characters on the line are stored in the string parameter, except for the

ENTER/newline, which is discarded.

returns NULL on end-of-file, otherwise the parameter s.

The parameter given to gets must be an already allocated array of characters, not an

uninitialised char * pointer; gets will never allocate memory.

{ char a[100]; gets(line); // This is correct

{ char a[100]; char *s; s=a; gets(s); // This is correct

{ char *s; s=new char[100]; gets(s); // This is correct

{ char *s; gets(s); // This is WRONG

The array given to gets must be big enough to hold any line that could conceivably be

input. C++ and C are incapable of telling how long an array is. If it is not long enough

for the data that is read, other data (and perhaps program code) will be overwritten.

Thus gets is not a safe function for use in critical applications.

User Avatar

Wiki User

17y ago

Still curious? Ask our experts.

Chat with our AI personalities

JudyJudy
Simplicity is my specialty.
Chat with Judy
ProfessorProfessor
I will give you the most educated answer.
Chat with Professor
RafaRafa
There's no fun in playing it safe. Why not try something a little unhinged?
Chat with Rafa
More answers

Both fgets() and gets() read a line terminated with a newline terminator, while gets() reads from stdin and fgets() reads from a specified file. Also, gets() strips the trailing newline from the result.

User Avatar

Wiki User

12y ago
User Avatar

Add your answer:

Earn +20 pts
Q: Difference between fgets and gets
Write your answer...
Submit
Still have questions?
magnify glass
imp