递归函数中带有readdir时出现分段错误

时间:2019-11-26 16:20:09

标签: c segmentation-fault coredump dirent.h

所以在运行时 中我在C中遇到了分段错误(没有-Wall编译错误或警告)。我找到了解决方案,但不明白为什么错误会首先出现。如果有人可以向我解释这一点,那就太好了。我正在学习C,并且想了解它不仅有解决方案。

void read_dir (const char *path){ 
  DIR *dir;
  struct dirent *object;

  dir = opendir(path);
  if (dir == NULL) return;

  object = readdir(dir);

  while (object != NULL) {
    char *name = object->d_name;
    char fullPath[300];
    sprintf(fullPath, "%s/%s", path, name); 
    object = readdir(dir);  //put it here **error** placement 1

    if (object->d_type == DT_DIR && strcmp(name,".") && strcmp(name,"..")) 
      read_dir (fullPath); 

    object = readdir(dir);// put it here **no error** placement 2
}   
    closedir(dir);
  }

代码像这样在main中运行

int main (){
  read_dir("..");
  return 0;
}

据我了解,seg err / core dump是在尝试读取不属于该程序的内存时读取的。

据我对回避的了解,只要函数不返回,它就会创建并让我的var存活,为什么简单的顺序更改会发生如此大的变化。

展示位置1的输出:

../.
../a.out
../scripts
../b.class
../b.java
../..
Segmentation fault (core dumped)

展示位置2的输出:

../.
../a.out
../scripts
../scripts/a.c
../scripts/b.c
../scripts/a.txt
../scripts/dir.c
../scripts/.
../scripts/a.out
../scripts/makefile
../scripts/c.c
../scripts/a.class
../scripts/char.c
../scripts/conf.h
../scripts/a.java
../scripts/..
../scripts/dir.backup
../b.class
../b.java
../..```

1 个答案:

答案 0 :(得分:1)

object = readdir(dir);  //put it here **error**

if (object->d_type == DT_DIR && strcmp(name,".") && strcmp(name,"..")) 
  read_dir (fullPath); 

如果对readdir的此调用返回了NULL,则您仍然可以通过尝试测试将进行段故障的NULL来取消引用object->d_type。在仍然需要访问它指向的内容时,您无法更改object