Home > Back-end >  C unhandled Exception while checking ARGV values
C unhandled Exception while checking ARGV values

Time:05-26

Can someone tell me why this code worked 10 minutes ago but keeps failing now?

I keep getting unhandled exception error. In the debug menu I am entering 32 and 12.5.

The code fails each time I try to check i > 0;

bool CheckArgInputs(char* inputs[], int numInputs)
{
    const char validChars[] = "., -eE0123456789";
    bool tester = false;
    
    for (int i = 0; *inputs[i] != 0; i  )
    {
        tester = false;

        for (int j = 0; j < sizeof(validChars); j  )
        {
            if (*inputs[i] == validChars[j])
            {
                tester = true;
            }
        }
        if (tester == false)
            return false;
        //else
        //  cout << "Good Input" << endl;
    }
}

int main(int argc, char* argv[])
{
    bool validInput = true;

    for (int i = 1; i < argc; i  )
    {

        validInput = CheckArgInputs(&argv[i], argc);

        if (validInput == false)
        {
            cout << "X" << endl;
            return 0;
        }
    }

    return 0;
}

CodePudding user response:

Your CheckArgInputs() function is coded to act like it is being given a pointer to an individual string, but main() is actually giving it a pointer to a pointer to a string. And then the function is not coded correctly to iterate the individual characters of just that string, it is actually iterating through the argv[] array one string at a time until it goes out of bounds of the array.

You are also not actually return'ing anything from CheckArgInputs() if the input string were valid.

Try this instead:

bool CheckArgInput(const char* input)
{
    const char validChars[] = "., -eE0123456789";
    
    for (int i = 0; input[i] != 0; i  )
    {
        for (int j = 0; j < sizeof(validChars)-1; j  )
        {
            if (input[i] != validChars[j])
            {
                return false;
            }
        }
    }

    return true;
}

int main(int argc, char* argv[])
{
    bool validInput = true;

    for (int i = 1; i < argc; i  )
    {
        validInput = CheckArgInput(argv[i]);
        if (!validInput)
        {
            cout << "X" << endl;
            return 0;
        }
    }

    return 0;
}
  • Related