被认为sscanf的安全使用? [英] Is sscanf considered safe to use?

查看:1223
本文介绍了被认为sscanf的安全使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的建议模糊的回忆,的sscanf 是坏的。我知道它不会溢出缓冲区,如果我使用的字段宽度说明,所以我的记忆中只是在玩把戏和我在一起?

I have vague memories of suggestions that sscanf was bad. I know it won't overflow buffers if I use the field width specifier, so is my memory just playing tricks with me?

推荐答案

我想这取决于你如何使用它:如果您要扫描的东西像 INT ,它的罚款。如果你在扫描一个字符串,它不是(除非有一个宽领域,我忘了?)。

I think it depends on how you're using it: If you're scanning for something like int, it's fine. If you're scanning for a string, it's not (unless there was a width field I'm forgetting?).

修改

这并不总是扫描字符串是安全的。

It's not always safe for scanning strings.

如果您的缓冲区的大小是一个常数,那么你当然可以将它指定为类似 20年代%。但是,如果它不是一个常数,你需要在格式字符串指定它,你需要做的:

If your buffer size is a constant, then you can certainly specify it as something like %20s. But if it's not a constant, you need to specify it in the format string, and you'd need to do:

char format[80]; //Make sure this is big enough... kinda painful
sprintf(format, "%%%ds", cchBuffer - 1); //Don't miss the percent signs and - 1!
sscanf(format, input); //Good luck

这是可能的,但非常容易出错,就像我在previous编辑做了(忘了照顾空终止的)。你甚至可能会溢出,格式字符串缓冲区。

which is possible but very easy to get wrong, like I did in my previous edit (forgot to take care of the null-terminator). You might even overflow the format string buffer.

这篇关于被认为sscanf的安全使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆