scanf is dangerous, but what is the reason?

We all know scanf / fscanf / sscanf is dangerous. But why? what is the exact reason?

I thought the ‘%s’ is a problem that causes buffer overflow and ‘fgets’ is a better solution. But is it the exact reason?

I pased a discussion by AndreyT and his discussion helps me figure it out:

Claiming that scanf is somehow analogous to gets in the respect is
completely incorrect. There’s a major qualitative difference between
scanf and gets: scanf does provide the user with
string-buffer-overflow-preventing features, while gets doesn’t.

the problem with scanf is that it is difficult (albeit possible) to
use properly and safely with string buffers. And it is impossible to
use safely for arithmetic input. The latter is the real problem. The
former is just an inconvenience.

More details are here:

Leave a Reply

Your email address will not be published. Required fields are marked *