如何prevent scanf函数用C导致缓冲区溢出? [英] How to prevent scanf causing a buffer overflow in C?

查看:565
本文介绍了如何prevent scanf函数用C导致缓冲区溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个code:

while ( scanf("%s", buf) == 1 ){

什么是至prevent可能缓冲区溢出的最佳方式,以便它可以传递随机长度的字符串?

What would be the best way to prevent possible buffer overflow so that it can be passed strings of random lengths?

我知道我可以通过调用例如限制输入字符串:

I know I can limit the input string by calling for example:

while ( scanf("%20s", buf) == 1 ){

不过我倒是preFER要能够处理任何用户输入。
或者不能被这个安全使用scanf函数做,我应该使用与fgets?

But I'd prefer to be able to process whatever the user inputs. Or can't this be done safely using scanf and I should use fgets?

推荐答案

在他们的著作实践编程的 (这是值得一读),Kernighan和派克讨论这个问题,他们通过使用的snprintf()来创建一个具有正确的缓冲区大小的字符串传递给解决 scanf()的系列函数。实际上:

In their book The Practice of Programming (which is well worth reading), Kernighan and Pike discuss this problem, and they solve it by using snprintf() to create the string with the correct buffer size for passing to the scanf() family of functions. In effect:

int scanner(const char *data, char *buffer, size_t buflen)
{
    char format[32];
    if (buflen == 0)
        return 0;
    snprintf(format, sizeof(format), "%%%ds", (int)(buflen-1));
    return sscanf(data, format, buffer);
}

请注意,这仍然限制输入为缓冲提供的大小。如果您需要更多空间,那么你所要做的内存分配,或者使用一个非标准的库函数,它的内存分配给你的。

Note, this still limits the input to the size provided as 'buffer'. If you need more space, then you have to do memory allocation, or use a non-standard library function that does the memory allocation for you.

请注意,2008年POSIX(2013年)的 scanf函数的版本() 系列函数支持的格式修改 M (分配分配字符)字符串输入(%S %C %[)。而不是采取一个的char * 参数,它需要一个的char ** 参数,并且分配了必要的空间,为珍惜它读取:

Note that the POSIX 2008 (2013) version of the scanf() family of functions supports a format modifier m (an assignment-allocation character) for string inputs (%s, %c, %[). Instead of taking a char * argument, it takes a char ** argument, and it allocates the necessary space for the value it reads:

char *buffer = 0;
if (sscanf(data, "%ms", &buffer) == 1)
{
    printf("String is: <<%s>>\n", buffer);
    free(buffer);
}

如果在的sscanf()函数无法满足所有的转换规范,那么所有它%MS分配的内存式的转换是在函数返回前释放。

If the sscanf() function fails to satisfy all the conversion specifications, then all the memory it allocated for %ms-like conversions is freed before the function returns.

这篇关于如何prevent scanf函数用C导致缓冲区溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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