Implicit declaration of 'gets'

Death_by_Ch0colate picture Death_by_Ch0colate · Dec 1, 2015 · Viewed 41k times · Source

I understand that an 'implicit declaration' usually means that the function must be placed at the top of the program before calling it or that I need to declare the prototype.
However, gets should be in the stdio.h files (which I have included).
Is there any way to fix this?

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
   char ch, file_name[25];
   FILE *fp;

   printf("Enter the name of file you wish to see\n");
   gets(file_name);
   fp = fopen(file_name,"r"); // read mode
   if( fp == NULL )
   {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
   }
}

Answer

P.P picture P.P · Dec 1, 2015

You are right that if you include proper headers, you shouldn't get the implicit declaration warning.

However, the function gets() has been removed from C11 standard. That means there's no longer a prototype for gets() in <stdio.h>. gets() used to be in <stdio.h>.

The reason for the removal of gets() is quite well known: It can't protect against the buffer overrun. As such, you should never use gets() and use fgets() instead and take care of the trailing newline, if any.