So i get an segmentation error in C, while runtime (no compiling Error or Warnings with -Wall). I found a solution but do not understand why the error occurred in first place. If someone could explain this to me it would be nice. I'm learning C right now and want to understand it not just have a solution.
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);
}
code is running in main like this
int main (){
read_dir("..");
return 0;
}
from what i understand seg err/core dump is when reading trying to read memory that does not belong to the program.
And from what i understand about recusion it creates and let my var alive as long as the function does not return so why does that simple change of order changes so much.
Output for placement 1:
../.
../a.out
../scripts
../b.class
../b.java
../..
Segmentation fault (core dumped)
Output for placement 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
../..```