I have seen people saying fgets is safer to use than gets and it avoids buffer overflow. I want to ask how. code :
Code:
int getstring(char *s, size_t n, FILE *fp)
{
char *p = NULL;
if (fgets(s, n, fp) == NULL)
{
fprintf(stderr, "getstring failed\n");
return (1);
}
else
{
if ((p = strchr(s, '\n')) != NULL)
{
*p = '\0';
}
}
return (0);
}
int main(void)
{
char s[20];
if (getstring(s, sizeof s, stdin)
{
fprintf(stderr, "main failed\n");
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
I tried to overflow the input string with more than 50-60 characters and absolutely no error message or anything was printed.