我写了一个简单的代码来读取一个目录,然后按最后修改时间对文件进行排序,但是下面的代码会因为段错误(核心转储)而崩溃,(在尝试访问 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 ,根据不同的编译器可能会出现不同的错误。
- 在
make_path
,endp
指向dir_name
的最后一个字符('\0'
)并试图将其从'\0'
更改为至'/'
无需在末尾插入字符串尾随字符 ('\0'
) 和realloc
dir_name
多一个字符 - 在
main
,const char *n_dir = "/home/psycho/Pictures";
不需要定义为指针,因为长度在编译时已知。事实上应该改为:const char n_dir[] = "/home/psycho/Pictures";
- 在
main
,endp
根本没有分配,所以strcpy(endp, ent->d_name);
复制到受限内存空间 - 在
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/