我不明白 valgrind 的条件跳转,我做了这个小函数,但即使它很小,也有这个条件跳转
这是函数:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *function(char *str)
{
int i = 0;
int a = 0;
char *cpy;
cpy = malloc(100);
while (str[i] != '\0')
{
if (str[i] == 'a')
cpy[a++] = 'b';
i++;
}
return (cpy);
}
int main(int ac, char **av)
{
char *str;
str = function(av[1]);
printf("%s\n", str);
}
当我像这样使用 valgrind 时
valgrind ./a.out "aa aa aaaaaaaaaaa"
它给了我 1 个错误
==3397== Conditional jump or move depends on uninitialised value(s)
==3397== at 0x4C2E4E8: strlen (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==3397== by 0x4EA1531: puts (in /lib64/libc-2.24.so)
==3397== by 0x400609: main (in /home/benoit.pingris/train/a.out)
这是什么意思? 谢谢。
最佳答案
首先,它有助于使用调试符号编译程序(使用 -g
选项)。这样,Valgrind 就能够产生更有用的诊断。
条件跳转不会发生在代码内部,而是在 main()
末尾调用 printf()
时发生。原因是您分配了变量 cpy,但这并没有初始化其内存。然后,您将在 str
中看到的每个 'a'
字符 'b'
复制到 cpy
中。但是,您没有在 cpy
末尾添加 NUL 终止符。当您尝试打印 cpy
时,C 库中的某些内容将读取 cpy
的初始化部分,从而触发来自 Valgrind 的错误消息。
您可以自己添加一个 NUL 终止符(cpy[a] = '\0';
在 return
之前),或者使用 calloc()
而不是 malloc()
。
关于C - 条件跳转(valgrind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41826414/