ISimion
ISimion

Reputation: 108

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.

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");
    }
}

Upvotes: 0

Views: 581

Answers (1)

kabanus
kabanus

Reputation: 25980

Observe when you exit the while:

dirent = readdir(dir)) != NULL

so, dirent == NULL. But then you have:

if(dirent->d_type == DT_DIR)

which is, dereferencing a NULL pointer - seg-faulty as they come. 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.

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);
        }
    }
}

Upvotes: 2

Related Questions