分段错误,无论我如何更改代码C++

Segmentation fault, no matter on how i change the code C++

本文关键字:何更改 代码 C++ 错误 分段      更新时间:2023-10-16

这是我的代码

#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)。由于此大小在编译时是不确定的,因此您必须计算要相互附加的两个字符串的长度,并使用newmalloc分配足够大小的缓冲区。

然而,在C++中执行字符串串联的最简单方法是忘记所有的C等价物,只需像这样使用::std::string

::std::string s = "hello ";
s += "world";