[英]Segmentation fault(core dumped) in recursively listing of directories and files in C, Linux
so basically the issue appears when I try to run a function which recursively prints the paths for files and directories . 因此,基本上,当我尝试运行以递归方式打印文件和目录路径的函数时,就会出现问题。 The issue that I am getting in terminal when I run the program is " Segmentation fault (core dumped) ".
我在运行程序时进入终端的问题是“ 分段错误(核心已转储) ”。
Any suggestions how I can solve this? 有什么建议可以解决这个问题吗?
EDIT: MAX_LEN defined as 2048. 编辑:MAX_LEN定义为2048。
This is the code: 这是代码:
void list_recursive(char* path){
DIR* dir;
struct dirent *dirent;
char * name = malloc(sizeof(char) * MAX_LEN);
dir = opendir(path);
if(dir != NULL){
printf("SUCCESS\n");
while((dirent = readdir(dir)) != NULL){
if(strcmp(dirent->d_name, ".") != 0 && strcmp(dirent->d_name, "..") != 0){
sprintf(name, "%s/%s", path, dirent->d_name);
printf("%s\n", name);
}
}
free(name);
if(dirent->d_type == DT_DIR){
list_recursive(dirent->d_name);
}
closedir(dir);
}
else {
printf("ERROR\n");
printf("invalid directory path\n");
}
}
Observe when you exit the while: 观察您何时退出一会儿:
dirent = readdir(dir)) != NULL
so, dirent == NULL
. 因此,
dirent == NULL
。 But then you have: 但是然后您有:
if(dirent->d_type == DT_DIR)
which is, dereferencing a NULL pointer - seg-faulty as they come. 也就是说,取消引用NULL指针-出现段错误。 Perhaps you wanted this if inside the while?
如果在片刻之内也许您想要此?
As an aside, to debug this I just stuck a bunch of printfs
in your code to pin-point the exact line of segmentation - that's good practice for small programs and a quick fix. printfs
,要调试此功能,我只是在代码中printfs
了一堆printfs
来精确定位分段的行-这对于小型程序和快速修复来说是一个好习惯。
This works for me (fixing the recursion argument as well): 这对我有用(也修复了递归参数):
while((dirent = readdir(dir)) != NULL){
if(strcmp(dirent->d_name, ".") != 0 && strcmp(dirent->d_name, "..") != 0){
sprintf(name, "%s/%s", path, dirent->d_name);
printf("%s\n", name);
if(dirent->d_type == DT_DIR){
list_recursive(name);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.