1

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>

void mp3files(char** result, int* count, const char* path) {
    struct dirent *entry;
    DIR *dp;

    dp = opendir(path);
    if (dp == NULL) {
        printf("Error, directory or file \"%s\" not found.\n", path);
        return;
    }

    while ((entry = readdir(dp))) {
        if ((result = (char**) realloc(result, sizeof (char*) * ((*count) + 1))) == NULL) {
            printf("error");
                return;
        }

        result[*count] = entry->d_name;
        (*count)++;
    }

    closedir(dp);
}

int main() {

    int* integer = malloc(sizeof (int));
    *integer = 0;

    char** mp3FilesResult = malloc(sizeof (char*));
        mp3files(mp3FilesResult, integer, ".");

    for (int i = 0; i < *integer; i++) {
        printf("ok, count: %d \n", *integer);
        printf("%s\n", mp3FilesResult[i]);
    }

    return (EXIT_SUCCESS);
}

It gives me segmentation fault. However, when I put this loop:

for (int i = 0; i < *integer; i++) {
    printf("ok, count: %d \n", *integer);
    printf("%s\n", mp3FilesResult[i]);
}

in the end of mp3files function, it works. And when I change the third parameter of mp3files function from "." to a directory which contains less then 4 files or directories, it works great. In other words, when variable mp3FilesResult points at less then 4 strings, it doesn't fail with segmentation fault.

Why does it keep doing it ?

Thanks in advance and sorry for my english.

eightShirt
  • 1,457
  • 2
  • 15
  • 29
VaclavDedik
  • 1,960
  • 4
  • 20
  • 27

1 Answers1

4

You pass in a char **, a pointer to a pointer to char, which is representing pointer to "string" which is representing "array of string". If you want to reallocate that array you must pass it by reference (pass a pointer to it) so you need a "pointer to array of string", or a char ***:

... myfunc(char ***result, ...)
{
    *result = realloc(*result, ...); // writing *result changes caller's pointer
}


...
char **data = ...;
myfunc(&data, ...);
Ben Jackson
  • 90,079
  • 9
  • 98
  • 150
  • 3
    Assign the result of `realloc` to a temporary pointer variable. If the `realloc` call fails and returns NULL, you risk losing track of your memory block, resulting in a memory leak. – John Bode May 11 '11 at 20:40