【问题标题】:C - Pointer to dynamic array in struct "Segmentation fault (core dumped)"C - 指向结构“分段错误(核心转储)”中的动态数组的指针
【发布时间】:2015-02-22 03:16:08
【问题描述】:

我正在编写一个 c 程序来从目录中读取文件和目录,然后指向在结构的数据中找到的元素的数量,并在同一结构的数据中指向动态数组中元素的名称.我做到了,它的输出是正确的。问题是当我运行程序时出现“分段错误(核心转储)”。

代码:

#include <stdio.h>
#include <dirent.h>

#define EXIT_FAILURE 1

typedef struct FileDir
{   
    int *n_files;
    char *file_name[];
} FileDir;

int get_files_within_dir(struct FileDir *fd)
{
    DIR *dir;
    int n_files;
    int index;

    n_files = 0;
  if ((dir = opendir ("/tmp")) != NULL) {
    /* counts all the files and directories within directory */
    while (readdir (dir) != NULL) {
      n_files++;
    }
    closedir (dir);
  } else {
    /* could not open directory */
    perror ("");
    return EXIT_FAILURE;
  }       

  char *file_name[n_files];
  struct dirent *ent;
  if ((dir = opendir ("/tmp")) != NULL) {
    /* gets all the files and directories within directory */
    index = 0;
    while ((ent = readdir (dir)) != NULL) {
      file_name[index++] = ent->d_name;      
    }
    closedir (dir);
  } else {
    /* could not open directory */
    perror ("");
    return EXIT_FAILURE;
  }      

  fd->n_files = n_files;  
  fd->file_name[0] = file_name[0];
  fd->file_name[1] = file_name[1];
  fd->file_name[2] = file_name[2];
  fd->file_name[3] = file_name[3];

  return 0;  
}

int main()
{   
    struct FileDir fd;
    get_files_within_dir(&fd);
    printf("%d\n", fd.n_files);
    printf("%s\n", fd.file_name[1]);
    printf("%s\n", fd.file_name[2]);
    printf("%s\n", fd.file_name[3]);    

    return 0;
}

输出:

[freitas@localhost src]$ ./file_dir 
21
..
geany_socket.fcda02b3
tmpiSdUX3
Segmentation fault (core dumped)

有趣的是,如果我只是将小于或等于 2 个值指向结构数据的动态数组,则不会显示错误消息。你有什么想法吗?

谢谢!

【问题讨论】:

  • 尝试使用调试器

标签: c arrays pointers dynamic struct


【解决方案1】:

您有 2 个问题,可能导致 SEGMENTATION FAULT

  1. n_files 字段是一个指针,你给它分配了一个整数,它应该声明为

    int n_files;
    
  2. 您永远不会为 file_name 字段分配空间,您至少应该提供一个固定大小,像这样

    char *file_name[1000];
    

    您可以使用malloc() 动态分配内存,但这是另一回事,需要解释。

注意:启用编译器警告将帮助您防止愚蠢的错误,例如int *n_files,然后执行fd-&gt;n_files = n_files;

【讨论】:

    【解决方案2】:

    n_files 不应该是指针

    typedef struct FileDir
    {   
     int n_files;
     char *file_name[];
    } FileDir;
    

    然后你的行

     printf("%d\n", fd.n_files);
    

    不会崩溃。尝试使用调试器查看结构

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 2023-03-09
      • 2018-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      • 2015-05-12
      • 2016-09-07
      • 2013-05-06
      相关资源
      最近更新 更多