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

问题描述 投票:1回答:2
const char path[] = "./folderidonthave";
struct stat stat_path;
stat(path, &stat_path);

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

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

c unix valgrind
2个回答
3
投票

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

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

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;

或者,更紧凑(假设您想将错误与“非目录”相同):

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

2
投票

如果对stat的调用失败怎么办? Valgrind将检查此情况,并在调用(可能)失败时,将您的“ stat_path”视为“未修改”(未初始化)数据。在声明中添加一个虚拟的初始值设定项列表将解决此问题:

    struct stat stat_path = {0,};

并且不要忘记检查stat函数的返回值是否成功:

if (stat(path, &stat_path) != 0) {
    // Error-handling...
}
//...
© www.soinside.com 2019 - 2024. All rights reserved.