Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could reading numbers using sscanf crash?

Tags:

c++

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

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?

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.

like image 306
Juraj Blaho Avatar asked Feb 15 '12 11:02

Juraj Blaho


2 Answers

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.

like image 160
Daniel Marjamäki Avatar answered Sep 21 '22 06:09

Daniel Marjamäki


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.

like image 31
Donald Duck Avatar answered Sep 22 '22 06:09

Donald Duck