简体   繁体   中英

Segmentation Fault With argv

I have a program that reads in a single argument from the command line and performs certain operations on it. I'm using argv and argc. When I fail to pass an argument to the program, it segfaults. I've tried checking if argc isn't a certain value and then printing the value out, but it still segfaults. Here's the code in question. Note that it works as expected when passed a single argument. Here's the code in question:

int main(int argc, char *argv[])
{

int numTimes = atoi(argv[1]);           //converts content of argv[1] into integer

if(argc != 2)
{
        printf("Enter a valid integer.");
}

You need to check argc before you try to access that argument. Just move the argc test to sometime before before you call atoi(argv[1]) .

Just check the number of arguments before trying to accessing a specific element. Something like this:

int main(int argc, char *argv[]) 
{ 

    if(argc < 2)
    { 
        printf("Enter a valid integer."); 
        return 0;
    }

    int numTimes = atoi(argv[1]); // now we're sure to have at least 1 argument passed

    // ...
}

您必须先进行检查, 然后再尝试访问参数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM