CodeMonkey
CodeMonkey

Reputation: 368

Memory corruption when traversing a file system

I am making a function that transverses all the sub files of a system and if it is a regular file prints out the file directory. It will print out a file if it is in the directory but once it tries to transverse a subdirectory it gives me a malloc() memory corruption error despite the fact that I am not mallocing anything.

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;
}

Upvotes: 1

Views: 193

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726899

The problem is that you are using strcat into a strdup-ed memory (which is the same as malloc-ed memory), without allocating enough space for the suffix.

To fix this problem, you need to use malloc+strcpy (or some other way of forming a string, e.g. sprintf) instead of strcat, and make sure that you allocate additional space to your string. In addition, you need to call free to avoid memory leaks:

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

Upvotes: 1

Related Questions