0
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <stdlib.h>

void listFilesRecursively(void *p);

struct data {
    char path[100];
};

int main(int argc, char* argv[])
{
    // Directory path to list files
    struct data *d= (struct data *)malloc(sizeof(struct data *));
    strcpy(d->path,argv[1]);
    listFilesRecursively(d);   //need to send a struct

    return 0;
}



void listFilesRecursively(void *p)
{
    struct data *d = (struct data *)p;

    char path[100];
    struct dirent *dp;
    DIR *dir = opendir(d->path);

    // Unable to open directory stream
    if (!dir)
        return;

    while ((dp = readdir(dir)) != NULL)
    {
        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
        {
            printf("%s\n", d->path);
            struct data *nd= (struct data *)malloc(sizeof(struct data *));

            // Construct new path from our base path
            strcpy(path, d->path);
            strcat(path, "/");
            strcat(path, dp->d_name);
            strcpy(nd->path,path);
            listFilesRecursively(nd);
        }
    }

    closedir(dir);
}

the idea is to list the files and subdirectories from a directory that I send as an argument. It works for few directories and then I get malloc(): corrupted top size Aborted (core dumped) I am probably blind and I dont see the issue, any suggestion? Thanks in advance!

Will Ness
  • 70,110
  • 9
  • 98
  • 181
zancudo
  • 325
  • 1
  • 3
  • 9
  • One thing you can do to make your life easier is get rid of the calls to `malloc()` and just declare your `struct data` objects as stack variables, e.g. `struct data d; memset(&d, 0, sizeof(d)); strcpy(d.path,argv[1]); listFilesRecursively(&d);` – Jeremy Friesner Nov 28 '20 at 02:21

1 Answers1

2

The lines

    struct data *d= (struct data *)malloc(sizeof(struct data *));

            struct data *nd= (struct data *)malloc(sizeof(struct data *));

are wrong because you have to allocate for the structure, not for the pointer for the structure.

They should be

    struct data *d= malloc(sizeof(*d));

            struct data *nd= malloc(sizeof(*nd));

or (if you stick to write type name for sizeof):

    struct data *d= malloc(sizeof(struct data));

            struct data *nd= malloc(sizeof(struct data));

Also note that casting the results of malloc() in C is discouraged.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70