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
的名称,这似乎很明显: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);
如果对stat
的调用失败怎么办? Valgrind将检查此情况,并在调用(可能)失败时,将您的“ stat_path”视为“未修改”(未初始化)数据。在声明中添加一个虚拟的初始值设定项列表将解决此问题:
struct stat stat_path = {0,};
并且不要忘记检查stat
函数的返回值是否成功:
if (stat(path, &stat_path) != 0) {
// Error-handling...
}
//...