VaclavDedik VaclavDedik - 9 months ago 62
C Question

C realloc inside a function

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

while ((entry = readdir(dp))) {
if ((result = (char**) realloc(result, sizeof (char*) * ((*count) + 1))) == NULL) {

result[*count] = entry->d_name;


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
function, it works. And when I change the third parameter of
function from "." to a directory which contains less then 4 files or directories, it works great. In other words, when variable
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.

Answer Source

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, ...);