merman said:
There is a question:
char *name;
printf("\nEnter your name > ");
scanf("%s", name);
or
gets(name);
What is most common way to read this?
char name[1024];
printf("Enter your name >");
fflush(stdout);
gets(name);
will read in the string.
(Not the call to fflush(), if you don't have a trailing newline this is
required to ensure output is visible).
The problem comes when the user enters more than 1023 characters. For some
applications, this is more theoretical than real, but for code that you
release to a third party it is essential to think about it, since some
malicious person could deliberately crash your program, even on some systems
hack into the system (because the overflow overwrites the function return
address, allowing arbitrary code to be run, if you know what you are doing).
fgets() will fix this problem, but adds a new one. What if over 1023
characters are entered, and the partly-read input is processed as whole? The
results are quite likely to be much worse than the undefined behaviour that
results from using gets(), since undefined behaviour is usually correct
behaviour (terminate the offending program with an error message), whilst no
operating system can guard against coded incorrect behaviour, such as
chopping off one of the hundred names of the Indian god brumin-brah and
getting you torn to pieces by his devotees for blasphemy.
Fortunately, fgets() leaves a trailing newline in the buffer, to indicate
that it has read the line correctly.
So what we need to do is
if(!strrchr(name, '\n'))
{
fprintf(stderr, "Input too long\n");
exit(EXIT_FAILURE);
}