c - 尝试获取文件名长度时出现段错误

标签 c

我已将段错误缩小到导致它的特定代码行。这是一个简单的示例,显示了我遇到的问题。

int main()
{
    char** files;
    int sum;
    int i;

    DIR *d;
    struct dirent *dir;
    d = opendir(".");
    if (d)
    {
            sum = file_sum();
            char* files[sum];
            i = 0;

            while ((dir = readdir(d)) != NULL)
            {
                    files[i] = dir->d_name;
                    i++;
            }

            closedir(d);
    }
    else
    {
            return -1;
    }

    int len = strlen(files[0]);    /*segmentation fault here*/

    return 0;
}

本质上,该程序所做的是从当前目录中获取所有文件的名称并将它们放入一个数组中。然后我将尝试获取所有文件名的大小,但我遇到了段错误。我的理论是,也许文件名不是以 null 结尾的?如果这是真的,我不确定是否有解决方法,但我们将不胜感激。

谢谢

编辑:抱歉,我在这里出错了。段错误仅在我尝试存储 strlen 返回值时发生,因为我现在已将代码更改为上面

最佳答案

在您的 if block 中,您定义了一个名为 files 的变量。这会在函数顶部屏蔽同名变量。 不是在更高范围内指定数组的大小,这似乎是您的意图。因此,当您退出 if block 时,内部 files 超出范围,并且外部 files 未初始化。然后取消引用未初始化的指针,导致核心转储。

您要做的是在 if block 中为您需要的内存动态分配必要的内存。

此外,检索到 dir->d_name 的目录名称可能会在每次调用 readdir 时被覆盖,因此您也需要为其分配空间。

编辑:

您也不需要单独的函数来获取文件计数。您可以使用默认大小和 realloc 分配数组以根据需要扩展:

int main()
{
    char** files;
    int sum;
    int i;

    DIR *d;
    struct dirent *dir;
    d = opendir(".");
    if (d)
    {
            int size = 10;
            sum = 0;
            files = malloc(size * sizeof(char *));   // allocate the array
            if (files == NULL) {
                perror("malloc failed");
                exit(1);
            }

            while ((dir = readdir(d)) != NULL)
            {
                    if (sum >= size) {
                        // if the array is full, realloc twice the size
                        char **tmp;
                        size *= 2;
                        tmp = realloc(size * sizeof(char *));
                        if (tmp == NULL) {
                            perror("realloc failed");
                            exit(1);
                        }
                        files = tmp;
                    }
                    files[sum] = strdup(dir->d_name);   // allocate and copy each string
                    sum++;
            }

            closedir(d);
    }
    else
    {
            return -1;
    }

    strlen(files[0]);

    // free the individual strings
    for (i=0; i<sum; i++) {
        free(files[i]);
    }
    // free the array
    free(files);

    return 0;
}

关于c - 尝试获取文件名长度时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34142909/

相关文章:

c - 将整数作为二进制发送时出现 PostgreSQL libpq "Integer out of range"错误

c - 矩阵邻居 C 代码

c - 使用 gcc 链接两个目标文件

c - pow 应该能够处理这样的事情 : why does my code freeze at this point?

将 C 转换为 MIPS64 汇编

c - Bitwise arthmetric 这将导致 true 或 false

复杂声明

c - 如何清理使用 read() 填充的缓冲区并继续读取同一缓冲区?

C - Gdb 不让我看到堆栈内存中的值

c - 在传递给函数本身的指针上调用 realloc() 是否安全?