How could reading numbers using sscanf crash?

那年仲夏 提交于 2019-12-05 00:52:22

I am a Cppcheck developer.

Yes this is a weird crash. With "huge data" it means millions of digits.

If you use the --verbose flag then cppcheck will actually write a little example code that usually crashes on linux computers.

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;
}

For your info I don't get a crash when I try this example code on visual studio.

I used g++ version 4.6.1 to compile.

The segmentation fault seems to be a bug in glibc.

I've just tested this with a similar program, which crashes in ubuntu 10.04, but works in ubuntu 12.04.

As Daniel Marjamäki said, his program crashes in 11.10, I believe the bug is fixed in between.

OK, consider this code:

int main(int argc, char *argv[]) {
    const char* data = "9999999999999999999999999.9999999999999999999999//i put alot more 9's there, this just to get the point through
    float a;
    int count = sscanf(data, "%f", &a);
    printf("%f",a);
}

the output of this program is "inf" - no crash. And I put a huge amounts of 9's there. So I suspect Cppcheck is just plain wrong about this.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!