3
votes

While doing cppcheck, cppcheck is showing 'invalid scanf' and it is saying:

scanf without field width limits can crash with huge input data on some versions of libc.

Does it give any crash for my program? How to get rid of this issue?

   int a;
   char str[32];
   int part[4];
   // after this i am storing some string in 'str'.
   a = sscanf(str, "%d%d%d%d", &part[0], &part[1], &part[2], &part[3]); // here i am getting that cppcheck portability error.
2

2 Answers

4
votes

How to get rid of this issue

By writing C++ rather than C, and using C++ Standard Library tools rather than the out-dated and often unsafe C Standard Library tools.

#include <iostream>
#include <sstream>

void test()
{
   std::string str("4 5 6 7");
   int part[4];

  std::istringstream ss(str);
  ss >> part[0]
    >> part[1]
    >> part[2]
    >> part[3];

}
1
votes

What you are getting is just a warning: some libc implementations might crash if, say, you give too long strings to %s etc. CPPCheck recommends you to use other, typesafe, c++ methods to achieve your aim (i.e. streams and std::to_string() convertors etc.)