cvalgrindcoredumpreaddir

segfault on readdir call


I'm trying to perform a readdir(): here is the code:

DIR *dp;
struct dirent *dirp;

if (dp = opendir("saves") == NULL) {
    my_printf("Cannot open saves directory.\n");
    return 84;
} else if ((dirp = readdir(dp)) == NULL) {
    printf("hello\n");
} else 
    while ((dirp = readdir(dp)) != NULL)
        printf("%s\n", dirp->d_name);

I've got a segfault on the while ((dirp = readdir(dp)) != NULL) and the program do not cross the else if statement.

Valgrind output :

==4398== Invalid read of size 4
==4398==    at 0x4AB99C3: readdir (in /usr/lib/libc-2.33.so)
==4398==    by 0x10C047: save_map (save_button.c:23)
==4398==    by 0x10C0ED: save_button_event (save_button.c:36)
==4398==    by 0x10BBA7: check_close (window_process.c:52)
==4398==    by 0x10A44F: main (my_world.c:19)
==4398==  Address 0x4 is not stack'd, malloc'd or (recently) free'd

Any idea?


Solution

  • if (dp = opendir("saves") == NULL)
    

    You missed the parens around the assignment here which you need because == has higher precedence than =.

    You've assigned the result of the comparison to dp which is certainly not a valid pointer.

    You need:

    if ((dp = opendir("saves")) == NULL)