遍历文件系统时内存损坏

时间:2015-02-16 04:36:12

标签: c ubuntu directory filesystems

我正在创建一个遍历系统所有子文件的函数,如果它是常规文件,则打印出文件目录。它将打印出一个文件,如果它在目录中,但是一旦它尝试横向子目录,它就会给我一个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;
}

1 个答案:

答案 0 :(得分:1)

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

要解决此问题,您需要使用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