首页 > 解决方案 > 核心转储在 char **指针上

问题描述

我知道分段错误发生在哪里,但不明白为什么。

我的主要功能是这样的:

int execute_line(char *line){
  char **arguments;

  int i = parse_args(arguments,line); //separates line in arguments

  printf("Number of tokens: %d \n",i); //prints number of total tokens

  printf("%s\n",arguments[0]); //print first token so I know it's not void

  int r = check_internal(arguments); //segmentation fault
}

虽然 parse_args 函数填充如下参数:

int parse_args(char **args, char *line){

   const char s[]= " \t\n\r";
   char *token;
   token = strtok(line, s);//separates line with the separators
   int i=0;
   char null[] = "(null)";
   while( token != NULL ) {
      if (token[0]=='#'){ //if the like begins with "comment" I don't care

          args[i]=null;
          return i;
      }else{
          args[i] = token;// else fills each char * of **args with a token
          printf("Parse_args()--> token %d: ",i);
          printf("%s\n",token);
          i++;
    }
  token = strtok(NULL, s); //separates again
   }
   args[i]=null; //ends with null

return i;

}

我不明白为什么它会在 parse_args 正确返回标记后给出分段错误(因此至少填充了 **arguments)但是当我调用 int r = check_internal(arguments); 它给了我分段错误,(如果我在函数的第一行打印它不会显示,所以我想那是断点(打印调试 ftw))。

谁能指出我缺少指向正确内存部分的指针的位置?

错误:分段错误(核心转储)

check_internal: int check_internal(char **args);

如果我的输入是:

hey ho letsgo

程序返回:

Parse_args()--> token 0: hey
Parse_args()--> token 1: ho
Parse_args()--> token 2: letsgo
Number of tokens: 3 
hey
Segmentation fault (core dumped)

感谢任何可以帮助我的人:D

标签: c

解决方案


调用时parse_argsarguments未初始化。然后在内部parse_args,当您分配给时,您取消引用这个未初始化的指针args[i]。这样做会调用未定义的行为,这在这种情况下表现为崩溃。

声明arguments为足以满足您的目的的指针数组:

char *arguments[100];

或者,如果您不知道您将拥有多少个参数,您可以改为传递 a 的地址char ** 并在读取参数时为其动态分配内存:

int parse_args(char ***args, char *line){

   const char s[]= " \t\n\r";
   char *token;
   token = strtok(line, s);//separates line with the separators
   int i=0;
   char null[] = "(null)";
   *args = malloc(1 * sizeof(char *));
   while( token != NULL ) {
      if (token[0]=='#'){ //if the like begins with "comment" I don't care

          (*args)[i]=null;
          return i;
      }else{
          (*args)[i] = token;// else fills each char * of **args with a token
          printf("Parse_args()--> token %d: ",i);
          printf("%s\n",token);
          i++;
      }
      *args = realloc(*args, i * sizeof(char *));
  token = strtok(NULL, s); //separates again
   }
   (*args)[i]=null; //ends with null

   return i;

} 

并这样称呼它:

char **arguments;

int i = parse_args(&arguments,line);

推荐阅读