我必须像在C中那样编码,但我遇到了一些问题。 在使用opendir打开目录后,如果我没有使用printf或puts打印路径名,我会在closedir执行时遇到核心转储错误但是如果我打印路径,代码就可以了。
const char * cwd=".";
DIR * dir=opendir(cwd);
//that print --> printf("%s",cwd);
if(dir==NULL){
puts("ohlala");
}
char * filename;
struct dirent * truc;
struct stat * filestat=malloc(sizeof(struct stat *));
while((truc=readdir(dir))!=NULL){
filename=truc->d_name;
if(strcmp(filename,"..")!=0 && strcmp(filename,".")!=0){
if(l==0){
printf("%-s ",filename);
}else if(l==1){
if(stat(filename,filestat)!=0){
printf("Erreur stat de %s\n",filename);
exit(1);
}
printf("%ld %-s ",filestat->st_ino,filename);
}
}
}
//gdb is telling me the probleme is here
closedir(dir);
return 0;
有什么想法吗?感谢。
答案 0 :(得分:3)
您没有正确分配filestat
:此行
struct stat * filestat = malloc(sizeof(struct stat *))
应该是
struct stat * filestat = malloc(sizeof(struct stat))
没有星号。目前,对stat
的调用会写入已分配的内存块,从而导致未定义的行为。
请注意,您无需动态分配filestat
:将其设为局部变量,并将&filestat
传递给stat
来电:
struct stat filestat;
...
if(stat(filename, &filestat) != 0) {
...
}
...
printf("%ld %-s ", filestat.st_ino, filename);