C realloc inside a function -
here 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, "."); (int = 0; < *integer; i++) { printf("ok, count: %d \n", *integer); printf("%s\n", mp3filesresult[i]); } return (exit_success); }
it gives me segmentation fault. however, when put loop:
for (int = 0; < *integer; i++) { printf("ok, count: %d \n", *integer); printf("%s\n", mp3filesresult[i]); }
in end of mp3files
function, works. , when change third parameter of mp3files
function "." directory contains less 4 files or directories, works great. in other words, when variable mp3filesresult
points @ less 4 strings, doesn't fail segmentation fault.
why keep doing ?
thanks in advance , sorry english.
you pass in char **
, pointer pointer char, representing pointer "string" representing "array of string". if want reallocate array must pass reference (pass pointer it) need "pointer array of string", or char ***
:
... myfunc(char ***result, ...) { *result = realloc(*result, ...); // writing *result changes caller's pointer } ... char **data = ...; myfunc(&data, ...);
Comments
Post a Comment