如何使用sscanf读取数字崩溃? [英] How could reading numbers using sscanf crash?
问题描述
Cppcheck在如下代码中检测到潜在的问题:
Cppcheck has detected a potential problem in a code like this:
float a, b, c;
int count = sscanf(data, "%f,%f,%f", &a, &b, &c);
它说:没有域宽度限制的scanf可能会崩溃,并带有大量数据。那怎么可能?这是某些sscanf实现中的已知错误吗?我知道数字可能会溢出(数字地),但是程序如何崩溃?
It says that: "scanf without field width limits can crash with huge data". How is that possible? Is that a known bug in some sscanf implementations? I understand that the numbers may overflow (numerically), but how could the program crash? Is that a false positive in cppcheck?
我发现了一个类似的问题: scanf Cppcheck警告,但答案并不完全令人满意。答案提到类型安全,但这在这里应该不是问题。
I have found a similar question: scanf Cppcheck warning, but the answer is not completely satisfying. The answer mentions type safety, but that should not be an issue here.
推荐答案
我是Cppcheck开发人员。
I am a Cppcheck developer.
是的,这是一次奇怪的崩溃。
Yes this is a weird crash. With "huge data" it means millions of digits.
如果使用--verbose标志,则cppcheck实际上会写一些通常在linux计算机上崩溃的示例代码。
If you use the --verbose flag then cppcheck will actually write a little example code that usually crashes on linux computers.
以下是在我的Ubuntu 11.10计算机上由于分段错误而崩溃的示例代码:
Here is an example code that crashes with a segmentation fault on my Ubuntu 11.10 computer:
#include <stdio.h>
#define HUGE_SIZE 100000000
int main()
{
int i;
char *data = new char[HUGE_SIZE];
for (int i = 0; i < HUGE_SIZE; ++i)
data[i] = '1';
data[HUGE_SIZE-1] = 0;
sscanf(data, "%i", &i);
delete [] data;
return 0;
}
对于您的信息,尝试该示例代码时不会崩溃在Visual Studio上。
For your info I don't get a crash when I try this example code on visual studio.
我使用g ++ 4.6.1版进行编译。
I used g++ version 4.6.1 to compile.
这篇关于如何使用sscanf读取数字崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!