top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Out of fgets() and gets() which function is safe to use and why?

+1 vote
351 views
Out of fgets() and gets() which function is safe to use and why?
posted Nov 18, 2015 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes
 
Best answer

The function fgets() function is safer to use. It checks the bounds, i.e., the size of the buffer and does not cause overflow on the stack to occur. gets() does not check the bounds.
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 parameter given to gets must be an already allocated array of characters, not an
uninitialised char * pointer; gets will never allocate memory.

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.

gets does NOT check the size of the buffer and overflow on the stack can occour. Because of this you should use fgets in preferance.

answer Nov 18, 2015 by Shivaranjini
Similar Questions
+7 votes
#include<stdio.h>

int &fun()
{
   static int x;
   return x;
}   

int main()
{
   fun() = 10;
   printf(" %d ", fun());

   return 0;
}

It is fine with c++ compiler while giving error with c compiler.

+2 votes

I know of "select()" which works using file descriptors.

However I want similar functionality to "select()" but for a simple function that returns an int.

So suppose, there's "int calculate_magic()" function and I want to allow it to work for 2 seconds, if it takes longer than that I want to move on.

If "calculate_magic()" wrote its answer to a file descriptor I could use "select()" but how to do it for the case I mentioned?

I need something like this for a simple game implementation where the player is allowed a maximum time to make a decision about their next move.
I
was hoping I can get something without having to deal with threads, etc.

+5 votes

Help me to write a C program which can generate list of numbers which are palindrome in decimal and octal notion. You can take some max as a limit find out all numbers which satisfy the given property between 1 to n.

+4 votes

Out of three prominent advance transport protocols (TCP, UDP and SCTP) which is the best to use and why should i use that protocol ?

...