Search code examples
ccrashprintfopendir

C Program crashes when calling Opendir after printf


I am writing a program to list the files within a folder. In the code below, it runs fine but if I un-comment

//printf("This makes the program crash.\n");

and run it again the program crashes. It will not print out "folder opened" so it is crashing on the opendir. It will also crash if I define 'd' inside the getfiles function instead of passing it in. I am compiling with MinGW. My program is below.

#include <stdio.h>
#include <dirent.h>

    void getfiles(DIR *d) {
        //DIR* d;
        struct dirent *dir;
        char* folder_dest;
        printf("Please enter name of upload folder.\n");
        scanf("%s", folder_dest);
        d = opendir(folder_dest);
        printf("folder opened\n");  //does not print when it crashes

        if (d) {
            while ((dir = readdir(d)) != NULL) {
                if( dir->d_type != DT_DIR) {
                    printf("%s\n", dir->d_name);
                }
            }
            closedir(d);
        }
    }

    int main(void) {
        DIR *d;
        //printf("This makes the program crash.\n");
        getfiles(d);
        return(0);
    }

Solution

  • char* folder_dest;
    scanf("%s", folder_dest)
    

    folder_dest is not initialized in your program and points at a random memory address. scanf will then invoked undefined behavior when writing characters. Use an character array instead of a char pointer. A better solution would be to use fgets plus sscanf instead of scanf.