【问题标题】:Conditional jump or move depends on uninitialised value after returning from function从函数返回后,条件跳转或移动取决于未初始化的值
【发布时间】:2020-12-04 09:51:05
【问题描述】:

在我的程序中,我想去掉非字母字符。 它们是用 char*pattern 编写的。它是在功能上完成的。在功能上,我打印出来没有问题,但返回后我收到警告: 有条件的跳转或移动取决于未初始化的值

看起来像:文字是:co*asd

   printf("%s\n", pattern); // printed normally line 149
   pattern = scan_opt_patern(pattern, &extra_character, //line150
            &letter_before, pattern_len);  //line 151
   printf("%s\n", pattern); // printed with cond jump //line 152

第二次 printf 正确打印文本,不会遗漏任何空格,但会出现条件跳转错误。

功能是:

char *scan_opt_patern(char *pattern, char *extra_character, 
    char *letter_before, int pateren_len)
{
  int counter_of_position = 0, pos_extra;
  char pattern_without_ex[pateren_len - 1];
  while (*(pattern + counter_of_position)){
    if (*(pattern + counter_of_position) == '+' ||
       *(pattern + counter_of_position) == '*' ||
        *(pattern + counter_of_position) == '?'){
      *(extra_character) = *(pattern + counter_of_position);
      *(letter_before) = *(pattern + counter_of_position - 1);
      pos_extra = counter_of_position -1;
    }
    if (*(extra_character) != '0')
      pattern_without_ex[counter_of_position] = *(pattern + counter_of_position+1);
    else
      pattern_without_ex[counter_of_position] = *(pattern + counter_of_position);

    counter_of_position ++;
  }
  pattern = pattern_without_ex;
  printf("%s.\n", pattern); // always printed without problem
  return pattern;
}

Valgrind 打印:

==11983== Conditional jump or move depends on uninitialised value(s)
==11983==    at 0x483EF49: strlen (vg_replace_strmem.c:461)
==11983==    by 0x48DEE94: __vfprintf_internal (vfprintf-internal.c:1688)
==11983==    by 0x48C7EBE: printf (printf.c:33)
==11983==    by 0x4016F7: check_if_match (try.c:152)
==11983==    by 0x4017BA: search_in_text (try.c:233)
==11983==    by 0x401403: main (try.c:72)

【问题讨论】:

  • 不确定我是否遵循...“条件跳转”是什么或在哪里?
  • 你能创建minimal reproducible example吗?
  • 我已经编辑了描述。

标签: c function pointers


【解决方案1】:

scan_opt_patern() 你可以

 char pattern_without_ex[pateren_len - 1];
 ...
 pattern = pattern_without_ex;
 ...
 return pattern;

因此,当函数返回并调用未定义行为时,您将返回已超出范围的变量的地址。

您有多种选择:

  1. pattern_without_ex 的缓冲区传递给函数
  2. malloc()分配内存,当你不再需要该值时,在调用函数中调用free()
  3. (不鼓励)使用static 变量

【讨论】:

    猜你喜欢
    • 2013-05-18
    • 2011-08-18
    • 2011-04-18
    • 2016-07-24
    • 2014-11-30
    相关资源
    最近更新 更多