You can use scanf() super safely but it can be a pain in the ass.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *data = NULL;
char format[16];
int length = 0;
int convert = 0;
puts("Please enter a string length.");
convert = scanf("%i", &length);
if (convert == 1 && length > 1)
{
data = malloc(1 + length);
sprintf(format, "%%%ds", length);
}
else
{
fputs("Bad string length entered.\n",stderr);
return 1;
}
printf("OK, enter your string (length = %d).\n", length);
convert = scanf(format, data);
if (convert == 1)
{
printf("Good job.\n\"%s\"\n", data);
}
else
{
fputs("There was a problem.\n",stderr);
}
free(data);
data = NULL;
return 0;
}
/*
Please enter a string length.
20
OK, enter your string (length = 20).
Low-calorie.beer
Good job.
"Low-calorie.beer"
*/
Basically you need to do that. I guess it could look worse, and I didn't check malloc(). Oh well. There's annoying things about scanf that won't be fixed, like not reading strings longer than one word.
[edit] It's not that scanf is a bad function that works poorly, but user input is frequently not formatted at all. Use scanf to read formatted files or something. It can be a lot of work to shoehorn this one way you know to get input into the program securely.[/edit]