gets() is risky to use!

Consider the below program.

filter_none

edit
close

play_arrow

link
brightness_4
code

void read()
{
   char str[20];
   gets(str);
   printf("%s", str);
   return;
}

chevron_right


The code looks simple, it reads string from standard input and prints the entered string, but it suffers from Buffer Overflow as gets() doesn’t do any array bound testing. gets() keeps on reading until it sees a newline character.

To avoid Buffer Overflow, fgets() should be used instead of gets() as fgets() makes sure that not more than MAX_LIMIT characters are read.

filter_none

edit
close

play_arrow

link
brightness_4
code

#define MAX_LIMIT 20
void read()
{
   char str[MAX_LIMIT];
   fgets(str, MAX_LIMIT, stdin);
   printf("%s", str);
  
   getchar();
   return;
}

chevron_right


Please write comments if you find anything incorrect in the above article, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up