1
int dir_contents(const char *folderName, char ** result) {
    struct dirent *entry;
    DIR *dir = NULL;
    dir = opendir(folderName);

    if (!dir) {
        printf("ERROR open dir:\n\tLine:%d\n\tFunction:%s\n",__LINE__,__func__);
        return 0;
    }

    *result = (char*)malloc(256 * sizeof(char));
    int i = 0;
    while ((entry = readdir(dir))) {
        i++;
        char *line = NULL;
        line = (char*)malloc(256 * sizeof(char));
        sprintf(line, "%s:%d\n", entry->d_name, entry->d_type);
        printf("%d:%s", i, line);
        strncat(*result, line, strlen(line) + 1);
        free(line);
    }

    closedir(dir);
    dir = NULL;

    return 1;
}

This code is a basic function to read a directory and returns by reference a string with all the contents of a directory

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • 1
    Couple of notes: `sizeof(char)` is `1`, and you don't need to/shouldn't cast `malloc` so you can simplify to: `*result = malloc(256);` – Chris Jun 05 '22 at 01:45
  • 3
    You also don't need to dynamically allocate `line` at all, as it is copied into `*result`, so that memory doesn't have to outlive the loop's scope. Just write `char line[256];`. – Chris Jun 05 '22 at 01:47
  • Any time you're `malloc`ing and `free`ing within the same block, the only reason to do that would be to avoid placing a very large amount of data on the stack. You might do it if the data needs to outlive the loop, but then you wouldn't `free` it. – Chris Jun 05 '22 at 01:48
  • Could you please express which compiler used? also please provide [MCVE] or simple complete code that can be run with others. This code now cant be compiled. – EsmaeelE Jun 05 '22 at 01:48
  • 3
    `strncat(*result, line, strlen(line) + 1);` is bad as `*result` does not point to a _string_. – chux - Reinstate Monica Jun 05 '22 at 01:54
  • 1
    @chux-ReinstateMonica: Indeed. Undefined behavior from accessing a string. – Joshua Jun 05 '22 at 02:02
  • I tried char line[256] and it gave me a different error:corrupted size vs. prev_size and i use gcc. Can you explain why *result doesnt point to a string? – Lamri Yacine Jun 05 '22 at 02:05
  • 1
    @LamriYacine: A slight mistake. It's `*result` that's pointing to uninitialized memory. That `strncat` call is doing something wild. – Joshua Jun 05 '22 at 02:08
  • @LamriYacine `*result` points to an allocated piece of memory. What _string_ is in it before `strncat(*result, line, strlen(line) + 1);`? – chux - Reinstate Monica Jun 05 '22 at 02:42

0 Answers0