分段错误,无论我如何更改代码C++
Segmentation fault, no matter on how i change the code C++
这是我的代码
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <cstring>
#include <iostream>
using namespace std;
bool endsWith(string const &value, string const &ending)
{
if(value.length() >= ending.length())
{
return (value.compare(value.length() - ending.length(), ending.length(), ending) == 0);
}
return false;
}
void listdir(const char *directory, const char *extension)
{
DIR *dir;
struct dirent *entry;
if(!(dir = opendir(directory)))
{
return;
}
while(entry = readdir(dir))
{
if(entry->d_type == DT_DIR)
{
char path[1024];
int len = snprintf(path, sizeof(path)-1, "%s/%s", directory, entry->d_name);
path[len] = 0;
if(strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
{
listdir(path, extension);
}
}
else
{
string file = entry->d_name;
if(endsWith(file, strcat((char *) ".", extension)) || extension == "*")
{
printf("%s n", entry->d_name);
}
}
}
closedir(dir);
}
int main(int count, char *parameters[])
{
const char *type = "*";
const char *path = ".";
if(count > 1)
{
path = parameters[1];
}
if(count > 2)
{
type = parameters[2];
}
if(count < 1 || count > 3)
{
return 0;
}
listdir(path, type);
return 0;
}
不管我在做什么,我总是会收到分段错误。
在debian下用g++编译它是没有问题的,但运行应用程序总是会出现"分段错误"
那怎么了?
您的错误出现在strcat((char *) ".", extension)
行,您试图将数据写入字符串文字的内存中。
字符串文字被加载到只读内存段中,并试图写入导致segfault的内容。
如果您希望使用strcat
,则必须提供足够大小的目标缓冲区(未进行检查,因此通常首选使用strncat
)。由于此大小在编译时是不确定的,因此您必须计算要相互附加的两个字符串的长度,并使用new
或malloc
分配足够大小的缓冲区。
然而,在C++中执行字符串串联的最简单方法是忘记所有的C等价物,只需像这样使用::std::string
:
::std::string s = "hello ";
s += "world";
相关文章:
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 在大括号内添加语句会更改代码功能?
- 更改代码::块上的默认保存文件类型
- 打印值会更改代码的输出
- 如何在不更改代码的情况下为所有C++函数设置属性
- 通过更改代码格式来计算结构向量中包含的双精度变量的平均值的不同结果?
- 通过将前向声明替换为包含来更改代码的含义
- 修复错误:在不更改代码的情况下获取临时地址
- 在运行时更改代码中属性的值
- 如何更改代码块中的文本颜色和控制台颜色
- 将C++串口奇偶校验更改代码从 Linux 移植到 Windows
- RPi_utils无法识别远程、如何更改代码
- 拆分.cpp文件而不更改代码
- 在不更改代码的情况下使用 .in 文件进行测试
- Visual Studio 2012尝试缩进代码块会更改代码
- 需要更改c++代码
- VC++ 2010:'missing type specifier'错误来来去去,无需更改代码
- 如何在Visual c++中强制POD类型的值初始化而不更改代码
- 如何使用lambda表达式更改代码
- 分段错误,无论我如何更改代码C++