简体   繁体   English

解析命令行参数时出现分段错误

[英]Segmentation fault when parsing command line arguments

I am getting a segmentation fault I am having trouble isolating the source of the fault. 我遇到了分段错误,无法隔离错误的来源。 I believe that for some reason argv and argc are not getting values, but I cannot figure out why. 我认为出于某种原因argv和argc无法获取值,但是我无法弄清楚原因。

Here is the first part of my code. 这是我的代码的第一部分。

int main(int argc, char **argv)
{
int i;
int numArrays = 0;
int test = 0;
int opt = 0;

printf ("Parsing....\n");  // This line gets printed
printf(argv);    // this one doesn't even if being flushed immediately after
printf(argc);    // when the previous line is deleted, this line also won't print
fflush(stdout); 
opt =  getopt(argc, argv, optString);  //  defined as optString = "qmc";

while (opt != -1) {
    printf (opt);
    switch (opt) {
    //prevents program from printing to a file
    case 'q':
        tofile = 1;
        break;
    // max size of the prime numbers
    case 'm':
        maxPrime = atoi(optarg);
        break;

    case 'c':
        numProcs = atoi(optarg);
        break;

    default:
        break;
    }
}

I'm tried to figure out what is going on, but I cannot see why argc and argv are not getting values. 我试图弄清楚发生了什么,但是我看不到argc和argv为什么没有获取值。 I have used this exact same parsing code before and it has worked perfectly. 我之前使用了完全相同的解析代码,并且运行良好。 Usually segmentation faults are pretty easy (accessing memory locations you shouldn't be), but there is no reason I shouldn't have access to my command line arguments. 通常,分段错误非常容易(访问您不应该访问的内存位置),但是没有理由我不应该访问命令行参数。

You are confused about how to use printf . 您对如何使用printf感到困惑。 What you're currently doing is a big no-no: 您当前正在做的事情是大禁忌:

printf(argv);
printf(argc);

The function expects a const char* string that specifies the format of the output and optional variable argument list. 该函数需要一个const char*字符串,该字符串指定输出和可选变量参数列表的格式。 You are passing a double-pointer, which is not a string, and an integer, which is not even a pointer! 您正在传递一个不是字符串的双指针和一个甚至不是指针的整数!

You want something like this: 您想要这样的东西:

printf( "Number of arguments: %d\n", argc );
for( int i = 0; i < argc; i++ ) {
    printf( "Arg %d: %s\n", i, argv[i] );
}

Read up on printf here: http://en.cppreference.com/w/c/io/fprintf 在此处阅读有关printf信息: http : //en.cppreference.com/w/c/io/fprintf

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

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