Max string length using scanf -> ANSI C

Solution 1:

I wasn't happy with any of these solutions, so I researched further, and discovered GNU GCC macro stringification

which can be used as:

#define XSTR(A) STR(A)
#define STR(A) #A
#define MAX_STR_LEN 100
scanf("%"XSTR(MAX_STR_LEN)"[^\n]s", sometext)

Maybe VS2010 offers something similar?

Solution 2:

I just want to avoid buffer overflow

Then don't use scanf(). At all.

If you are scanning lines of text, don't #define MAX_STR either. You can haz LINE_MAX in <limits.h> (if you are targeting POSIX compatible systems):

char buf[LINE_MAX];
fgets(buf, sizeof(buf), stdin);

should do the trick.