4

Below piece of code throws Unvalidated integer value is received from std::stoi klocwork error. If *it contains invalid range or non integer value then catch block will be executed. But we are getting klocwork error in second for loop as tainted data 'value' is used in loop boundary. How to fix this issue?

#include <vector>
#include <string>
#include <iostream>

int main()
{
    int value = 0;
    std::vector<std::string> test;
    test.push_back("1");
    test.push_back("2");

    for (std::vector<std::string>::iterator it = test.begin(); it != test.end(); ++it)
    {
        try
        {
            value = std::stoi(*it);
        }
        catch (...)
        {
            return -1;
        }

        for (int i = 0; i < value; i++)
        {
            //...
            //...
        }

    }

    return 0;
}
Arun
  • 2,247
  • 3
  • 28
  • 51
  • 3
    Looks like you've actually outsmarted your analyzer on that one. Maybe just disable it locally? – Bartek Banachewicz Feb 06 '18 at 13:17
  • 2
    I think I'd resolve it by not using klockwork ... `value` is always assigned (as you nicely initialize it to 0). Meaning even if stoi does throw it's got a valid value – UKMonkey Feb 06 '18 at 13:18
  • I wonder if there's some kind of comment macro like `//NO_KLOKWORK` you can wrap around the code you want it to suppress like you can with cppcheck and lcov – Gillespie Feb 06 '18 at 13:42
  • Maybe it doesn't recognize that you would avoid the flow with incorrect value. Technically outside of `try` `value` might be unvalidated. Does it help if you move the loop inside the `try` block? FWIW I don't think this is a particularly good question for SO, because one cannot easily recreate problem and validate answers. A good question is whether klokwork is right or wrong, but this should probably be taken to their support... – luk32 Feb 06 '18 at 13:57

1 Answers1

1

i have tried the same code with Klocwork version 2020.2 and not seeing any issues in the code. Possibly, this False Positive might have resolved in the latest version of Klocwork.

Please do try to test the code with Klocwork latest version.