使用无效输入时的Segfault

Jas*_*son 1 c unix segmentation-fault

-help在命令参数中使用无效输入或标志时,我收到了段错误.它是Unix expand实用程序的重新创建,它应该以类似的方式处理错误.

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

  char help1[]= "-help";
  char help2[]= "--help";

  int spaces; //number of spaces to replace tabs

  if (argc==1){ //if only one argument in stack

    //check if asking for help
    if ( (strcmp(argv[1], help1)==0) || (strcmp(argv[1], help2)==0) )
      printHelp(); 

    else
      printError(); //otherwise, print error message    

    //right number of tokens are provided, need to validate them
    } else if (argc>=2){
      spaces= atoi(argv[2]); //assign it to spaces

      parse_file(spaces); //open the stream and pass on
  }     
  return 0;

}
Run Code Online (Sandbox Code Playgroud)

我的printerror方法:

void printError(){
  fprintf(stderr, "\nInvalid Input.\n");
  fprintf(stderr, "The proper format is myexpand -[OPTION] [NUMBER OF SPACES]\n");
  exit(1);
}
Run Code Online (Sandbox Code Playgroud)

当我尝试无效输入或帮助标志时,我得到一个段错误.为什么这样,因为我正在检查第一个标志是否有帮助?

小智 5

如果将单个命令行参数传递给您的程序,则argc == 2需要替换

if (argc==1){ //if only one argument in stack
Run Code Online (Sandbox Code Playgroud)

if (argc==2){
Run Code Online (Sandbox Code Playgroud)

请注意,在大多数系统中argv[0]是程序名称,在这种情况下argc至少为1.您可以将其argc视为元素的数量argv.如果你正在测试argv[1],你期望argv至少有两个元素(argv[0]argv[1]),因此argc需要至少2个.