【问题标题】:Memory corruption when traversing a file system遍历文件系统时内存损坏
【发布时间】:2015-04-16 13:26:57
【问题描述】:

我正在制作一个横穿系统所有子文件的函数,如果它是常规文件,则打印出文件目录。如果文件在目录中,它会打印出一个文件,但是一旦它尝试遍历子目录,它就会给我一个malloc() memory corruption error,尽管我没有分配任何东西。

void Traverse(char* dir)
{
    struct stat buffer;
    struct stat *s=&buffer;
    struct dirent* file;
    DIR* currentDir;
    // printf("%s \n",dir);
    if((strstr(dir,"./")!=NULL)||(strstr(dir,"../")!=NULL))
    return;
    currentDir = opendir(dir);
    if (lstat(dir,s)==0)
    {

        if(S_ISREG(s->st_mode))
        printf("%s \n", dir);

        else if (S_ISDIR (s->st_mode))
        {
            while((file= readdir(currentDir))!=NULL)
            {
                char* path = strdup(dir);
                strcat(path,"/");
                strcat(path,file->d_name);
                Traverse(path);
            }
            closedir(currentDir);
        }
    }
    else
    return;
}

【问题讨论】:

  • 我认为 strcat 可能会在这里产生问题

标签: c ubuntu directory filesystems


【解决方案1】:

问题是您将strcat 用于strdup-ed 内存(与malloc-ed 内存相同),而没有为后缀分配足够的空间。

要解决此问题,您需要使用malloc+strcpy(或其他一些形成字符串的方式,例如sprintf)而不是strcat,并确保为您的细绳。另外,需要调用free来避免内存泄漏:

size_t len = strlen(dir)+strlen(file->d_name)+2; // 1 for '/' + 1 for '\0' => 2
char* path = malloc(len);
// Check the result of malloc here
sprintf(path, "%s/%s", dir, file->d_name);
Traverse(path);
free(path); // Avoid memory leaks

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    相关资源
    最近更新 更多