c - 从目录读取时出现段错误

标签 c unix segmentation-fault

我正在尝试读取 2 个目录并将其内容放入两个动态数组中 当我阅读时,我遇到了段错误。我唯一能看到它的地方是在循环中添加?

 #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char** argv) {

  // get directory parameters



  DIR *dirA;
  DIR *dirB;
  struct dirent *dA;
  struct dirent *dB;

  //check if dir A exists
  if (!(dirA = opendir(argv[1])))
    fprintf(stderr,"Failed to open directory %s \n",argv[1]);
  //check if dir B exists
  if (!(dirB = opendir(argv[2])))
    fprintf(stderr,"Failed to open directory %s \n",argv[2]);
  //open dir
  dirA= opendir(argv[1]);
  dirB= opendir(argv[2]);
  int sizeA;
  int sizeB;

  while (0!= (dA = readdir(dirA)))
   {

      sizeA++;

    }

  while (0!= (dB = readdir(dirB)))
    {
      sizeB++;
    }
  char**contentsA;
  char**contentsB;
  contentsA=(char**)(malloc(80*sizeof(char*)));
  contentsB=(char**)(malloc(80*sizeof(char*)));
  int i=0;
  while (0!= (dA = readdir(dirA)))
    {
     contentsA[i]=dA->d_name;
      i++;
    }
  i=0;
     while (0!= (dB = readdir(dirB)))
   {
     contentsB[i]=dB->d_name;
   }
     for ( i=0; i<sizeA; i++)
{

  printf("%s\n", contentsA[i]);
}

  for ( i=0; i<sizeB; i++)
{

  printf("%s\n", contentsB[i]);
}
  printf("size a = %d \n size b = %d\n", sizeA, sizeB);
  return (EXIT_SUCCESS);
   }

我认为问题可能出在最后一个循环

最佳答案

有很多错误。

其中之一是您存储目录条目中的名称指针,但不复制字符串数据。您只是复制指针,该指针指向您不拥有的内存。所有名称很可能都指向内存中的同一位置。

此外,您永远不会使用每个目录中的项目计数,而是硬编码 80 个条目。如果超过 80 个,您将覆盖随机内存。

您还应该关闭该目录并重新打开它,或者(更好)调用 rewinddir()在第二次循环之前,否则您的目录流已耗尽。

关于c - 从目录读取时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21482956/

相关文章:

c - ruby C 扩展 : character values over 127

c - 当我在 MATLAB 中单击 UI 按钮时,我需要交替使用 X 和 O

c - 为什么我的 HTTP 服务器不知道客户端何时断开连接?

php - 重用PHP Unix套接字文件

c - 超出 read() 的缓冲区大小

linux - 如何检测内存不足的段错误?

c++ - 这个2D数组如何访问分配的索引?

c++ - 析构函数上的段错误

c++ - 传递函数指针

c - 为什么使用 `execl` 而不是 `system` 会阻止我的程序运行?