【问题标题】:c - scandir, memory fault core dumped errorc - scandir,内存故障核心转储错误
【发布时间】:2016-11-21 19:26:56
【问题描述】:

我正在尝试列出有关指定目录中文件的信息,但我收到了 Memory Fault Core Dumped 错误。 列出目录方法:

int listdir(char *path) {

struct dirent **dirlist;
int n;  
char *fullpath;
n = scandir(path, &dirlist, NULL, alphasort);

while (n--) {
    strcpy(fullpath, path);
    strcat(fullpath, dirlist[n]->d_name);
    (void)printfinf(fullpath);      

    free(dirlist[n]);
}
free(dirlist);

return 0;
}

Printfinf 方法 - 此方法工作正常,打印出有关文件的信息

int printfinf(char *path) { 

struct stat info;
struct passwd *pswd;
lstat(path,&info);          
pswd = getpwuid(info.st_uid);
char *modestr = mode2str(info.st_mode, getuid(), getgid());
char *timestr = time2str(info.st_mtime);

printf("%s %s %10lld %s %s\n", modestr, pswd->pw_name, info.st_size, timestr, path);

char c = modestr[0];

if(c == 'd')
    return FTYPE_DIR;
else if(c == 'f')
    return FTYPE_REG;
else if(c == 'e')
    return FTYPE_EXE;
else if(c == 'l')
    return FTYPE_LNK;
else return FTYPE_OTH;  

}

【问题讨论】:

  • 您好!你为什么从你的问题中删除代码?现在完全不清楚了。
  • 不要从您的问题中删除代码。欢迎来到堆栈溢出。请注意,在这里说“谢谢”的首选方式是投票赞成好的问题和有用的答案(一旦你有足够的声誉这样做),并接受对你提出的任何问题最有帮助的答案(这也给出了你的声誉小幅提升)。请查看About 页面以及How do I ask questions here?What do I do when someone answers my question?

标签: c scandir


【解决方案1】:

你需要为目标路径字符串分配内存,你没有。

如果你在终端输入man strcpy,那么你会知道strcpy()的第一个参数应该指向预分配的内存,改变你的代码来使用这样的数组

char fullpath[PATH_MAX];

会解决问题。

警告:不要忽略警告!!!

很明显,要么忽略它们,要么让它们静音,忽略函数的返回值是错误的(大多数时候),你应该检查函数返回什么来执行良好的错误处理。

另外,不要使用strcat()。而是这样做(在更改上述建议后

int length;
length = snprintf(fullpath, sizeof(fullpath), "%s/%s", path, dirlist[n]->d_name);
if ((length >= sizeof(fullpath)) || (length == -1)) {
    fprintf(stderr, "Either, there is no room for the "
                    "target string or an error occurred\n");
}

【讨论】:

  • 好的,谢谢,我对 c 很陌生,所以这有点奇怪,它对我有用,然后突然停止了,所以我很担心
  • @AhamadBoali 这被称为未定义行为,它发生在c。它有时可以工作,但突然间......哦!对不起,这就是你说的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 2014-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多