Ankuj
Ankuj

Reputation: 723

Crash in C++ Code

I am trying to list all files in a directory recursively. But my code crashes without giving any error. When the given file is directory I recursively call the function or else print its name.

I am using dirent.h

int list_file(string path)
{
    DIR *dir;
    struct dirent *ent;
    char  *c_style_path;
    c_style_path = new char[path.length()];
    c_style_path = (char *)path.c_str();
    dir = opendir (c_style_path);
    if (dir != NULL) {

        /* print all the files and directories within directory */
        while ((ent = readdir (dir)) != NULL) {
            if(ent->d_type == DT_DIR && (strcmp(ent->d_name,".")!=0) && (strcmp(ent->d_name,"..")!=0))
            {
                string tmp = path + "\\" + ent->d_name;
                list_file(tmp);
            }
            else
            {
                cout<<ent->d_name<<endl;
            }
        }
        closedir (dir);
    } else {
        /* could not open directory */
        perror ("");
        return EXIT_FAILURE;
    }
    delete [] c_style_path;
    return 0;
}

I am not getting as to what I am doing wrong here. Any clues ?

Upvotes: 0

Views: 539

Answers (1)

hmjd
hmjd

Reputation: 121961

This is the cause:

c_style_path = (char *)path.c_str();
//...
delete[] c_style_path;

as it is delete[]ing memory that it should not and probably results in a double free when path goes out of scope at the end of the function.

Just use path.c_str() when you require const char*:

dir = opendir (path.c_str());  

Note that storing the pointer returned by std::string::c_str() is quite dangerous as it can easily lead to a dangling pointer if the std::string instance goes out of scope.

Upvotes: 5

Related Questions