why gets() is not working?

gets is unsafe because you give it a buffer, but you don’t tell it how big the buffer is. The input may write past the end of the buffer, blowing up your program fairly spectacularly. Using fgets instead is a bit better because you tell it how big the buffer is, like this:

const int bufsize = 4096; /* Or a #define or whatever */
char buffer[bufsize];

fgets(buffer, bufsize, stdin);

…so provided you give it the correct information, it doesn’t write past the end of the buffer and blow things up.

Slightly OT, but:

You don’t have to use a const int for the buffer size, but I would strongly recommend you don’t just put a literal number in both places, because inevitably you’ll change one but not the other later. The compiler can help:

char buffer[4096];
fgets(buffer, (sizeof buffer / sizeof buffer[0]), stdin);

That expression gets resolved at compile-time, not runtime. It’s a pain to type, so I used to use a macro in my usual set of headers:

#define ARRAYCOUNT(a) (sizeof a / sizeof a[0])

…but I’m a few years out of date with my pure C, there’s probably a better way these days.

Leave a Comment