C++代码崩溃
Crash in C++ Code
我正在尝试递归列出目录中的所有文件。但是我的代码崩溃而没有给出任何错误。当给定文件是目录时,我递归调用该函数或以其他方式打印其名称。
我正在使用 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;
}
我不清楚我在这里做错了什么。 有什么线索吗?
这是原因:
c_style_path = (char *)path.c_str();
//...
delete[] c_style_path;
因为它delete[]
内存,它不应该并且可能会导致双释放,当path
在函数结束时超出范围时。
只需在需要const char*
时使用path.c_str()
:
dir = opendir (path.c_str());
请注意,存储 std::string::c_str()
返回的指针非常危险,因为如果std::string
实例超出范围,它很容易导致指针悬空。
相关文章:
- 为什么所有C++编译器都会崩溃或挂起此代码
- 使用 g++7 构建的代码在访问未对齐的内存时崩溃
- 您好,我实际上想了解以下代码.有人可以详细说明代码它到底在做什么吗?为什么它会在第 31 行崩溃
- 无法访问的代码如何导致我的程序崩溃?
- C++代码崩溃并具有无限循环
- 由于指针算法错误,代码在 memcpy 中崩溃
- 为什么在同一条件变量上使用多个互斥锁会使此代码崩溃?
- 运行简单的.oct文件时Octave崩溃,我的代码出了什么问题?
- 为什么代码会崩溃?(在CPP中)
- 赋值运算符在我制作类模板时使代码崩溃
- 为什么抓取窗口标题的代码会导致应用崩溃?
- 类似的代码.一个工作,一个崩溃.为什么?
- 为什么这段代码崩溃了
- 为什么此代码在此 Trie 实现中使用映射 c++ 中的指针崩溃?
- 为什么此代码会崩溃?(我是C 的新手)
- 程序过早结束,可能已经崩溃了.退出代码0xc0000005
- C++ - 代码在Visual Studio中完美运行,但命令行中的.exe不断崩溃
- 如何在导致应用程序崩溃的代码中修复指令
- 运行时,程序崩溃(代码块C++)
- 是我的编译器将适当的代码优化为无用的崩溃代码