C Lang - 结构数组和段错误(核心转储)

标签 c

我写了一个简单的代码来读取一个目录,然后按最后修改时间对文件进行排序,但是下面的代码会因为段错误(核心转储)而崩溃,(在尝试访问 lsf[0] 和 lsf[ 时发生) 1] ),如何解决这个问题,请帮忙,谢谢:

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

typedef struct {
  char *name;
  unsigned long lasted;
} sort_file;

char *make_path(char *path) {
  char *endp = path + strlen(path);
  *endp++ = '/';
  return endp;
}

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

  const char *n_dir = "/home/psycho/Pictures";
  char *dir_name = strdup(n_dir);

  char *endp = make_path(dir_name);

  DIR *dir;
  struct dirent *ent;
  struct stat attr;

  int size = 150;
  int count = 0;
  sort_file **lsf = malloc(size * sizeof(sort_file *));
  printf("[Logging] : %d => %d  \n", sizeof(sort_file), sizeof(sort_file *));
  if ((dir = opendir(n_dir)) != NULL) {
    while ((ent = readdir(dir)) != NULL) {

      if (ent->d_name[0] == '.') {
        continue;
      } else if (ent->d_type == DT_DIR) {
        strcpy(endp, ent->d_name);
        stat(dir_name, &attr);

        lsf[count] = malloc(sizeof(sort_file));
        lsf[count]->lasted = (unsigned long)attr.st_mtime;
        lsf[count]->name = malloc((strlen(ent->d_name) )* sizeof(char));

        sprintf(lsf[count]->name, "%s", ent->d_name);
        printf("[Logging] : --- %lu --- %d --- %s  \n", lsf[count]->lasted,
               count, lsf[count]->name);


        count++;

      }
    }
    closedir(dir);

  } else {
    return 0;
  }

  while (count--) {
    printf("[Logging] : --- %lu --- %d --- %s  \n", lsf[count]->lasted, count,
           lsf[count]->name);
  }
  return 0;
}

最佳答案

此代码包含一些内存 panic ,根据不同的编译器可能会出现不同的错误。

  1. make_path , endp指向 dir_name 的最后一个字符( '\0' )并试图将其从 '\0' 更改为至'/'无需在末尾插入字符串尾随字符 ( '\0' ) 和 realloc dir_name 多一个字符
  2. main , const char *n_dir = "/home/psycho/Pictures";不需要定义为指针,因为长度在编译时已知。事实上应该改为:const char n_dir[] = "/home/psycho/Pictures";
  3. main , endp根本没有分配,所以 strcpy(endp, ent->d_name);复制到受限内存空间
  4. main , lsf[count]->name = malloc((strlen(ent->d_name) )* sizeof(char));应该再分配一个单元,因为尾随 '\0' :lsf[count]->name = malloc((strlen(ent->d_name) + 1 )* sizeof(char));

最后我发现了一个逻辑错误: if (ent->d_name[0] == '.') { ...使程序跳过“.”、“..”以及以“.”开头的所有其他目录(Linux 隐藏文件夹)。您可以使用0 == (strcmp(ent->d_name, ".") * strcmp(ent->d_name, ".."))

关于C Lang - 结构数组和段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35008043/

相关文章:

c - 用原子替换条件?

c - i686-w64-mingw32/include/shlobj.h 中的一些奇怪的代码

c - 如何添加循环?

c++ - 通过软件提高 IR 串行可靠性

C/Fortran 二维数组(基础)

c - 是否可以将两个具有不同签名的函数作为参数传递给另一个函数?

C 位移位 : right operand considered for implicit type-conversion?

java - 如何在Java中处理C字符数组

c - 在 C 中从堆栈上的 Int 中正确读取 Char

c - printf 不起作用