简体   繁体   English

argv的分段错误

[英]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. 我正在使用argv和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. 我试过检查argc是否不是某个值,然后将其打印出来,但它仍然存在段错误。 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. 尝试访问该参数之前,需要检查argc Just move the argc test to sometime before before you call atoi(argv[1]) . 只需将argc测试移至调用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

    // ...
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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