在外部函数中标记化后,字符串数组项出现段错误

问题描述 投票:0回答:1

我正在尝试构建一个运行时命令行工具,但不明白为什么当我尝试对用户输入的字符串进行标记时会出现分段错误。

str_utils.c
文件中,表达式
printf("token: %s\n", tokens[i]);
被正确求值并打印数组的内容,但是在
user_input.c
文件中,如果我用
%p
打印指针,一切都很好,但是一旦尝试使用
%s
进行打印,出现分段错误。所以看起来我无法将单个令牌存储在数组中
tokens

这是代码:

// str_utils.c

int str_utils_split(char *str, char *delimiter, char **tokens,
                    int *tokens_count) {

  char *local_str = strdup(str);

  for (char *token = strtok(local_str, delimiter); token != NULL;
       token = strtok(NULL, delimiter)) {

    tokens = realloc(tokens, sizeof(char *) * (++(*tokens_count)));

    if (tokens == NULL) {
      fprintf(stderr, "realloc failed! Exiting!");
      return 1;
    }

    /* Am doing something wrong here? I ended up doing this because
       I read strtok was not doing any allocation
    */
    tokens[*tokens_count - 1] =
        strcpy((char *)calloc(strlen(token) + 1, sizeof(char)), token);
  }

  // or there?
  tokens = realloc(tokens, sizeof(char *) * (*tokens_count + 1));
  tokens[*tokens_count + 1] = 0;

  for (int i = 0; i < *tokens_count; i++) {
    printf("tokenin called fn: %s\n", tokens[i]);
  }

  free(local_str);

  return 0;
}
// user_input.c

char command_line_buffer[100];

void ui_parse_command(char *line, ui_command_t *command_obj) {

  char **cmd_tokens = malloc(sizeof(char *));
  char *delimiter = " ";
  int tokens_count = 0;

  str_utils_split(line, delimiter, cmd_tokens, &tokens_count);
  
  for (int i = 0; i < tokens_count; i++) {
    printf("token in calling fn: %p\n", cmd_tokens[i]); // OK
    printf("token in calling fn: %s\n", cmd_tokens[i]); // seg fault
  }
}

void ui_start_prompt(void (*callback)(ui_command_t *)) {

  printf("auralizer> ");
  ui_command_t command_obj;

  while (fgets(command_line_buffer, sizeof(command_line_buffer), stdin) !=
         NULL) {

    ui_parse_command(command_line_buffer, &command_obj);
    callback(&command_obj);
    printf("auralizer> ");
  }
}

我尝试过使用和不使用本地副本,在 split 函数中使用或不使用本地

tmp_tokens
数组,我尝试从
user_input.c
中的 NULL 指针开始,我将其转向各个方向,它总是可以编译,但总是会发生在同一个地方陷入段错误。

正确的输出是(正确的输出只发生过一次,然后在我重新启动程序后再次崩溃):

auralizer> tralala lala
token in called fn: tralala
token in called fn: lala

token in calling fn: tralala
token in calling fn: lala

重新执行程序后(

printf("%s")
):

auralizer> tralala lala
token in called fn: tralala
token in called fn: lala

[1]    27102 segmentation fault (core dumped)  ./bin/auralizer

打印指针 (

printf("%p")
):

auralizer> tralala lala
token in called fn: tralala
token in called fn: lala

token in calling fn: 0x557717df4cb0
token in calling fn: 0x557717df4cd0

我该如何解决这个问题?有什么想法吗?非常感谢!

arrays c string pointers segmentation-fault
1个回答
0
投票

感谢@Someprogrammerdude和@AndersK,我可以重新调整我的想法并纠正代码。请参考上面的评论。 再次感谢!

© www.soinside.com 2019 - 2024. All rights reserved.