Valgrind 根据未初始化的值报告条件跳跃或移动,但我不明白为什么

Valgrind reports conditional jump or move depending on uninitialised value(s), but I don't see why

const char path[] = "./folderidonthave";
struct stat stat_path;
stat(path, &stat_path);

if ( S_ISDIR(stat_path.st_mode) ) {
  return 1;
}
return 0; 

我仍然不明白为什么 Valgrind 对此有问题,因为条件变量似乎已初始化。

如果调用stat失败怎么办? Valgrind 将对此进行检查,并且在调用(可能)失败时,它将您的 'stat_path' 视为 'untouched'(未初始化的)数据。在声明中添加一个虚拟初始化列表将解决这个问题:

    struct stat stat_path = {0,};

并且不要忘记检查 stat 函数中的 return 值以查看它是否成功:

if (stat(path, &stat_path) != 0) {
    // Error-handling...
}
//...

鉴于您尝试 stat 的路径名称,这似乎很明显:stat() 失败,并且您声明的 struct stat stat_path 仍未初始化,因此您的 if 将根据未初始化的数据分支。

检查 stat() 的 return 值是否有错误:

int res;

res = stat(path, &stat_path);
if (res != 0) {
    // Handle the error somehow.
    perror("stat failed");
    return 0; // Return something appropriate here.
}

if (S_ISDIR(stat_path.st_mode))
    return 1;

return 0;

或者,更简洁(假设你想像 "not a directory" 一样对待错误):

return !stat(path, &stat_path) && S_ISDIR(stat_path.st_mode);