cklocwork

Unvalidated integer value is received from 'atoi'


For the following code, klocwork reports Unvalidated integer value 'val' is received from 'atoi' and can be used to access array

int main(int argc, char **argv)
{
    int i = 0;
    int val = 0;
    for (i = 0; i < argc; i++)
    {
        if (argv[i])
        {
            val = atoi(argv[i]);
            ......
            ......
        }
    }
    return 0;
}

I have no clue to solve this issue. If argv[i] is not a number then atoi will return 0. What is klocwork expecting here?


Solution

  • Well, the first obvious advice here is: stop using atoi. atoi is for sketching, not for real code. atoi does not have any failure feedback mechanisms and produces undefined behavior on overflow. Functions from ato... group have been semi-officially semi-abandoned in C95. Since that moment they have been just tagging along purely for backward compatibility. I have no idea why they are still not officially deprecated.

    You want to convert a string to integer - use strtol and remember to check for errors by analyzing errono and/or the return value. And, as it has been already suggested, if you are using the resultant value as an array index, it is a good idea (and for a value that comes from the outside world - it is a must) to make sure the index is in the proper range.