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);
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 grea开发者_开发技巧t. 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.
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, ...);
精彩评论