簡體   English   中英

C - 指向struct“Segmentation fault(core dumped)”中動態數組的指針

[英]C - Pointer to dynamic array in struct “Segmentation fault (core dumped)”

我正在編寫ac程序來從目錄中讀取文件和目錄,然后指出在結構數據中找到的元素數量,並將動態數組中元素的名稱指向同一結構的數據中。 我做到了,它的輸出是正確的。 問題是當我運行程序時出現“分段故障(核心轉儲)”。

編碼:

#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的值指向結構數據的動態數組,則錯誤消息不會顯示出來。 你有什么主意嗎 ?

謝謝!

您有2個問題,可能導致SEGMENTATION FAULT

  1. n_files字段是一個指針,你為它分配了一個整數,它應該被聲明為

     int n_files; 
  2. 你沒有為file_name字段分配空間,你應該至少提供一個固定的大小,就像這樣

     char *file_name[1000]; 

    你可以使用malloc()動態分配內存,但這是另一回事,它需要解釋。

注意 :啟用編譯器warnigns將幫助您防止像int *n_files這樣的愚蠢錯誤,然后執行fd->n_files = n_files;

n_files不應該是指針

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

然后你的線

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

不會崩潰。 嘗試使用調試器查看結構

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM