【发布时间】:2019-05-07 08:55:40
【问题描述】:
我正在使用 dirent.h 库扫描目录以查找其中包含的所有文件,并将指向结果对象的指针存储在数组中。我一直在关注这个old SO question,描述了数组中结构指针的存储,但我在实现过程中遇到了问题。
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc, char **argv)
{
DIR *d = NULL;
struct dirent *dir = NULL;
struct dirent *d_array[50]; //big overkill array to avoid realloc
size_t n = 0; //number of items
d = opendir("scandir"); //name of directory to search
if(d)
{
while((dir = readdir(d))!=NULL) {
//d_array[n] = malloc(sizeof(struct dirent));
d_array[n++] = dir;
}
closedir(d);
}
for(size_t i = 0;i<n;i++) {
printf(d_array[n]->d_name);
free(d_array[n]);
}
free(d_array);
return 0;
}
运行上述代码会导致分段错误:11。我认为这可能是因为我为结构正确分配了内存(如注释掉的 malloc 所示),但包含它会产生以下错误:
error: assigning to 'struct dirent *' from incompatible type
'void *'
我不明白为什么d_array[n] = malloc(sizeof(struct dirent))(来自有关该主题的多个帖子的逐字记录)会出现这种不兼容的类型错误。如果使用不合适,为什么会出现段错误?
【问题讨论】:
-
你是如何编译这段代码的?你用什么命令?
-
你是用 C++ 编译器编译这个吗?符合标准的 C 编译器不应抱怨将
malloc()的返回值分配给任何对象指针类型的对象。 -
@xing 不错,但不能解决分配错误。新错误是
a.out(3319,0x7fff74201300) malloc: *** error for object 0x7fb772003218: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug ...Abort trap: 6