Given the following program:
#include <stdio.h>
int main()
{
char buf[1024];
scanf("%s", buf);
printf("----> %s", buf);
return 0;
}
which is executed as follows:
grep ....| a.out
or
echo ....| a.out
I get a Segmentation fault error. Can anyone explain why?
from scanf man:
s Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null character (‘\0’), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
specifying maximum field width will prevent stack overrun
and to ensure stack no overrun on printf use memset:
so, programm will be: