C++代码崩溃

Ank*_*kuj 0 c++ crash

我试图以递归方式列出目录中的所有文件.但我的代码崩溃而没有给出任何错误.当给定文件是目录时,我递归调用该函数或者打印其名称.

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

我不知道我在这里做错了什么.有线索吗?

hmj*_*mjd 5

这是原因:

c_style_path = (char *)path.c_str();
//...
delete[] c_style_path;
Run Code Online (Sandbox Code Playgroud)

因为它delete[]不应该是内存,并且当path函数结束时超出范围时可能会导致双重释放.

只需path.c_str()在需要时使用const char*:

dir = opendir (path.c_str());  
Run Code Online (Sandbox Code Playgroud)

请注意,存储返回的指针std::string::c_str()非常危险,因为如果std::string实例超出范围,它很容易导致悬空指针.